javascriptgoogle-chrome-extensionfirefox-addonjavascript-objectscontent-script

What kind of objects are shared between different worlds in Javascript?


The objects I defined in page script seem not accessible in content script for an extension. But the two scripts do share some variables such as window, document, etc. Is there a way to expose some objects in one world to be used in another world?

I set a variable in page script like "window.myvar=123" but I cannot access it like "alert(window.myvar)" in content script(undefined). But the other components of the window object are the same across the two worlds.


Solution

  • In Chrome you need to inject into the MAIN world to access JS artifacts added by a page script, then you can exchange data by CustomEvent for generic structured-cloneable data or MouseEvent for DOM nodes, example. Note that it can be intercepted by other extensions or the page, and preventing it is complicated, see the source code of Violentmonkey.

    In Firefox you can use wrappedJSObject directly.