Chrome扩展程序:是否有扩展程序侦听页面上的事件? [英] Chrome extension: have an extension listen for an event on a page?

查看:1069
本文介绍了Chrome扩展程序:是否有扩展程序侦听页面上的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展名为im的网站,现在我的扩展程序每分钟检查一次数据库的更新。

I have a chrome extension that im making for my site, currently i have the extension checking the database every minute for updates.

是否有扩展名在实际页面上听一个事件?

Is it possible to have the extension listen for an event on the actual page?

类似这样的

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_script。 content_script拥有对DOM的完全访问权限,您可以绑定到页面上的所有事件。

you need to add a content_script. content_script have full access to the DOM and you can bind to all events on page

只需将其添加到清单文件

just add this to the menifest file

"content_scripts":[{
    "matches":["http://*/*","https://*/*"],
    "js":"your injected script.js"
}]

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

同样来自你的问题,它看起来像你将使用自定义事件,所以你的content_scrip js将会类似于这个

also from your question it looks like you going to be working with a custom event so your content_scrip js is going to be something similar to this

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

后台页面应该侦听一条消息。

the background page should listen for a message.

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

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

then you can trigger the Event from all scripts on the page...

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

这篇关于Chrome扩展程序:是否有扩展程序侦听页面上的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆