Can the window object be modified from a Chrome extension? [duplicate]

You can’t, not directly. From the content scripts documentation:

However, content scripts have some limitations. They cannot:

  • Use chrome.* APIs (except for parts of chrome.extension)
  • Use variables or functions defined by their extension’s pages
  • Use variables or functions defined by web pages or by other content scripts

(emphasis added)

The window object the content script sees is not the same window object that the page sees.

You can pass messages via the DOM, however, by using the window.postMessage method. Both your page and content script listen to the message event, and whenever you call window.postMessage from one of those places, the other will receive it. There’s an example of this on the “Content Scripts” documentation page.

edit:
You could potentially add some methods to the page by injecting a script from the content script. It still wouldn’t be able to communicate back with the rest of the extension though, without using something like postMessage, but you could at least add some things to the page’s window

var elt = document.createElement("script");
elt.innerHTML = "window.foo = {bar:function(){/*whatever*/}};"
document.head.appendChild(elt);

Leave a Comment