سؤال

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?

هل كانت مفيدة؟

المحلول

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:

  1. 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.
  2. 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 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top