chrome扩展,在popup页面,给页面对象绑定点击事件,获取当前tab加载页面的DOM对象信息。本chrome扩展功能主要用于获取百度搜索输入框中用户输入的关键字。效果如下

chrome扩展获取页面dom对象信息

  源代码如下

注意:以下文件全部以utf-8文件编码保存

manifest.json


    {
      "name": "chrome扩展获取页面dom对象信息",
      "manifest_version": 2,
      "version": "1.0",
      "author":"showbo,http://www.coding123.net",
      "description": "chrome扩展,在popup页面,给页面对象绑定点击事件,获取当前tab加载页面的DOM对象信息。本chrome扩展功能主要用于获取百度搜索输入框中用户输入的关键字。",
      "browser_action": {"default_popup": "popup.html"},
      "content_scripts": [{"matches": ["*://*/*"],"js": ["baidu.js"]}],
      "permissions": ["*://*/*","tabs"]
    }

popup.html

注意事项:chrome扩展不支持inline-script,绑定事件的代码需要放到外部js文件中,也不能直接在DOM对象上添加click事件

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>chrome extension获取页面DOM对象</title></head>
<body><pre>browser_action中的default_popup指定的页面<br />
页面中DOM对象如何绑定事件并且获取当前页面的DOM对象信息</pre>
<a id="a" href="#">点击获取百度搜索输入框中的关键字</a>
<script src="bindEvent.js"></script></body></html>
bindEvent.js
var a = document.getElementById('a');
a.onclick = function () {//给对象绑定事件
    chrome.tabs.getSelected(null, function (tab) {//获取当前tab
        //向tab发送请求
        chrome.tabs.sendRequest(tab.id, { action: "GetBaiduKeyWord" }, function (response) {
            alert(response.kw);
        });
    });
}
baidu.js
chrome.extension.onRequest.addListener(//监听扩展程序进程或内容脚本发送的请求
    function (request, sender, sendResponse) {
        if (request.action == "GetBaiduKeyWord") {
            sendResponse({ kw: document.forms[0].wd.value });
        }
    }
);

  注意:chrome.tabs.sendRequest和chrome.extension.onRequest这2个对象在版本的chrome中将被废弃,使用chrome.runtime.sendMessage和chrome.runtime.onMessage代替。


   由于本人的chrome版本为25,好像没有支持chrome.runtime对象,chrome.runtime为undefined(据说 chrome.runtime 对象chrome22+就支持了。搞毛。。?),懒得升级chrome,所以就没用chrome.runtime对象。


  所以如果chrome扩展出错没有效果,可能是这2个对象的问题。

  源代码压缩包下载:chrome扩展获取百度搜索输入框关键字