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

源代码如下
注意:以下文件全部以utf-8文件编码保存
manifest.json
{
"name": "chrome扩展获取页面dom对象信息",
"manifest_version": 2,
"version": "1.0",
"author":"showbo,http://www.w3dev.cn",
"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><br /> <a id="b" 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.kw+"-JSON");
});
});
}
document.getElementById('b').onclick = function () {
chrome.tabs.getSelected(null, function (tab) {
chrome.tabs.sendRequest(tab.id, { action: "SubmitForm" }, function (response) {
alert(response.kw.kw + "-JSON");
});
});
}
baidu.js
chrome.extension.onRequest.addListener(//监听扩展程序进程或内容脚本发送请求的请求
function (request, sender, sendResponse) {
if (request.action == "GetBaiduKeyWord") {
sendResponse({ kw: { kw: document.forms[0].wd.value } });
}
if (request.action == "SubmitForm") {
document.forms[0].submit();
}
}
);
注意: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扩展获取百度搜索输入框关键字
chrome扩展调试安装:下载好压缩包后解压到一个目录中,然后打开chrome进入扩展程序管理里面,勾上“开发者模式”,点击“载入正在开发的扩展程序...”,然后选择解压后的文件夹加载chrome扩展,打开百度后输入关键字进行测试。
加支付宝好友偷能量挖...

原创文章,转载请注明出处:chrome扩展获取页面dom对象信息

