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.
✅ The standard parts of elements and attributes in DOM/window
implemented per the specification by the browser explicitly e.g. document.body
, elem.dataset.foo
, window.scrollY
⭕ It doesn't include the unknown "expando properties" added by JS code e.g. elem.foo = 1
or window.foo = 1
✅ Ids of setTimeout, setInterval, requestAnimationFrame - note that it means the page can clear them trivially.
✅ DOM/window
events
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.