Chrome扩展程序:有扩展程序可以监听页面上的活动吗?

13 javascript google-chrome-extension

我有一个chrome扩展程序,我正在为我的网站,目前我有扩展程序检查数据库每分钟更新.

是否可以让扩展程序在实际页面上侦听事件?

像这样的东西

this.trigger('sendUpdate', data) //this happened on the page

this.on(sendUpdate, function(){ //this is what the chrome extension listens for
    //do stuff with data
})
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 24

你需要添加一个content_script.content_script具有对DOM的完全访问权限,您可以绑定到页面上的所有事件

只需将其添加到清单文件中即可

"content_scripts":[{
    "matches":["http://*/*","https://*/*"],
    "js":"your injected script.js"
}]
Run Code Online (Sandbox Code Playgroud)

您可以获得更多信息http://developer.chrome.com/extensions/content_scripts.html

从您的问题看,您似乎将使用自定义事件,因此您的content_scrip js将类似于此

document.addEventListener('yourEventName', function(e){
   //send message to ext
   var someInformation = {/*your msg here*/}
   chrome.extension.sendMessage(someInformation, function(response) {
      //callback
   });
}, false);
Run Code Online (Sandbox Code Playgroud)

后台页面应该监听消息.

chrome.extension.onMessage.addListener(function(myMessage, sender, sendResponse){
    //do something that only the extension has privileges here
    return true;
 });
Run Code Online (Sandbox Code Playgroud)

然后你可以从页面上的所有脚本触发事件......

var evt = document.createEvent('Event');
evt.initEvent('yourEventName', true, true);
var some_element = document;
some_element.dispatchEvent(evt);
Run Code Online (Sandbox Code Playgroud)