The "chrome" in the article on MDN does not refer to "Google Chrome", but to extension code that runs with Chrome privileges (look here for other meanings of "chrome" in Firefox).
In Google Chrome / Chromium, content scripts run in a different environment than the web page (that means that window
in the content script is different from window
in the web page).
However, when you send a message from the content script to the page, event.source
will be identical to the window
of the page. So, to verify that the message was really sent from a (content) script within the same page, you could use if (event.source === window) { ... }
.
If you want to send a message to another content script (in the same tab), then you have two options:
- If the frames are located at different origins, or if the content scripts are located in different tabs, then you have to send a message to the background page, which in turn passes the message to the target content script using the Chrome extension message passing APIs.
- If the communicating frames are located at the same origin, then their variables can directly be shared without using the message passing API. Refer to their
window
objects usingtop
,parent
,<HTMLIFrameElement>.contentWindow
,frames[index]
, etc.
Another (hackish) way to get a message from the one content script to another is through the chrome.storage
API. At the receiving end, bind a chrome.storage.onChanged
event. To "send" a message, use chrome.storage.local.set
. Don't forget to remove the key-value pair once you have (not) received the message.