20

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?

Something like this

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
})

2 Answers2

34

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"
}]

you can get more info https://developer.chrome.com/docs/extensions/mv2/content_scripts/

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);
Sitian Liu
  • 1,156
  • 10
  • 14
Josh
  • 3,264
  • 1
  • 23
  • 35
  • do you have an example on how to listen for an event from the content script –  Feb 12 '13 at 19:16
0

For anyone reading this in 2023, the sendMessage method has moved to chrome.runtime.sendMessage.

See documentation for manifest v3 (MV3): https://developer.chrome.com/docs/extensions/mv3/messaging/

nohehf
  • 355
  • 2
  • 9