2

What I'm trying to do is trigger an event from a web page and catch it inside a content script injected in that webpage. Both the page and the content script have their one instance of jQuery loaded, they don't have access to each other's variables but have access to the same DOM.

Is it possible to do this using jQuery events? How do they actually work in the background?

Page:

$('#elementID').trigger('stateChange', state)

Content script:

$('#elementID').on('stateChange', function(event, state) {...})
Nick Dima
  • 1,587
  • 2
  • 18
  • 36
  • After thinking more about it, I guess jQuery keeps all the event handlers in a variable somewhere and references them from there when a trigger is called. So there's no way they can be shared between the two instances... – Nick Dima Aug 01 '12 at 17:10
  • Catching an event from the page in the content script. For doing this I'm injecting my own js file in the page that acts as a bridge between the page and the content script. I know I can do it using HTML events and writing the messages inside a div or something. But I was curios if it can be done with jQuery events. – Nick Dima Aug 01 '12 at 21:58
  • 1
    Content scripts cannot directly access the page's global scope. So, it's not possible to use jQuery events to transfer data. Do you need an example of passing creating and triggering events between a page and a content script? I recall that I've posted an answer with code example in the past. – Rob W Aug 01 '12 at 22:08
  • If you have something handy, yes, thank you! – Nick Dima Aug 02 '12 at 09:57
  • See [this answer](http://stackoverflow.com/a/9636008/938089). I think/hope that you're capable enough of understanding the code. – Rob W Aug 02 '12 at 10:00
  • Just tested an approach using the 'HTML5' function postMessage() and it seems to work! It's really simple and clean. – Nick Dima Aug 02 '12 at 11:06
  • That also works. I'd say, post a working example + explanation as an answer, so that others can also benefit from the solution. – Rob W Aug 02 '12 at 12:23

1 Answers1

3

This is not doable with jQuery events. The easiest way to do it is by using the HTML5 api window.postMessage(). There's a good description and example on this in the Google Chrome extensions documentation: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication

Nick Dima
  • 1,587
  • 2
  • 18
  • 36