Reputation: 12073
According to this article on MDN, using postMessage to pass messages to and from a content script in chrome is not secure because can't properly define a source property, and that it's targetOrigin is difficult to securely pass to a potentially malicious site. Is this still true. Are there any other ways to confirm the source of a received message, and to only send messages to a specific content script exclusively? Or are there any alternatives to using content scripts altogether?
Upvotes: 1
Views: 1797
Reputation: 349042
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:
window
objects using top
, 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.
Upvotes: 5