user240993
user240993

Reputation:

Chrome extension: have an extension listen for an event on a page?

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

Upvotes: 20

Views: 20065

Answers (1)

Josh
Josh

Reputation: 3284

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

Read the documentation here

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

Upvotes: 34

Related Questions