Chrome Extension – Passing object from page to context script

The global variables of a content script and a page-level injected script are isolated.

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

Emphasis mine.

To pass the data to your content script, you don’t have to employ extra DOM elements. You just need custom DOM events.

// Content script
// Listen for the event
window.addEventListener("FromPage", function(evt) {
  /* message is in evt.detail */
}, false);

// Page context
var message = {/* whatever */};
var event = new CustomEvent("FromPage", {detail: message});
window.dispatchEvent(event);

See this answer for far more details.

Leave a Comment