Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Chrome扩展:让扩展侦听页面上的事件?_Javascript_Google Chrome Extension - Fatal编程技术网

Javascript Chrome扩展:让扩展侦听页面上的事件?

Javascript Chrome扩展:让扩展侦听页面上的事件?,javascript,google-chrome-extension,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 }) 您需要添加一个内容脚本。con

我有一个为我的网站制作的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
})

您需要添加一个内容脚本。content\u脚本具有对DOM的完全访问权限,您可以绑定到页面上的所有事件

只需将其添加到menifest文件中

"content_scripts":[{
    "matches":["http://*/*","https://*/*"],
    "js":"your injected script.js"
}]
你可以得到更多信息

另外,从您的问题来看,您将要处理一个自定义事件,因此您的内容scrip js将类似于此

document.addEventListener('yourEventName', function(e){
   //send message to ext
   var someInformation = {/*your msg here*/}
   chrome.extension.sendMessage(someInformation, function(response) {
      //callback
   });
}, false);
背景页面应侦听消息

chrome.extension.onMessage.addListener(function(myMessage, sender, sendResponse){
    //do something that only the extension has privileges here
    return true;
 });
然后您可以从页面上的所有脚本触发事件

var evt = document.createEvent('Event');
evt.initEvent('yourEventName', true, true);
var some_element = document;
some_element.dispatchEvent(evt);

您有关于如何从内容脚本中侦听事件的示例吗