In the chrome extension, how to send a cross-source message from parent script content to script content in a specific child iframe

I am developing a Chrome extension with a manifest that currently allows access to all hosts. Background script embeds content scripts in all frames. After loading the DOM, the contents of the script in the top page / frame begin to move through the DOM tree. When a walker encounters an iframe, it needs to be informed of the specific script content associated with that iframe (possibly cross) in order to get started and includes some serialized data with this message. The parent window pauses execution and waits for the child to complete it, and send the message back, which it runs along with the serialized data. Then the parent continues his work. I tried two approaches to this problem:

  • frameElement.contentWindow.postMessage: this works most of the time, but not always. Sometimes a message is never received by the script message event listener associated with the iframe. I could not confirm the reason, but I think that the listeners are attached in front of my listener, calling event.stopImmediatePropagation(). For example, on the yahoo homepage ( https://www.yahoo.com ) when sending a message to my script content related to iframe source https://s.yimg.com/rq/darla/2-9-9/html /r-sf.html , the message is never accepted. This is related to iframe ads. Perhaps blocking messages is intentional. There is no error sending the message, and I use targetOrigin from "*".
  • chrome.runtime.sendMessage: I can send a message to the original page, but I can’t understand how to tell the background page which frame to send this message to. The contents of the parent window of the script do not know the chrome extension frameId associated with the element of the child frame that it encountered in passing the DOM. Therefore, he cannot tell the background page how to direct the message.

In paragraph 2, I tried two methods that I found here in stackoverflow:

  • , question: iframe window.frames , . iframe, window.parent.frames, , , . , window.frames ( iframe , ).
  • 1 frameElement.name . , iframe window.name. , window.name frameElement.name iframe. , , name iframe .

script, iframe, DOM?

+4
1

chrome.runtime.sendMessage script, chrome.runtime.onMessage ( "" ) url frameId. ( , , ) , chrome.tabs.sendMessage frameId.

( ), chrome.webNavigation.getAllFrames. , , .

postMessage/onMessage

frameElement.contentWindow.postMessage: , . script, iframe. , , , , event.stopImmediatePropagation()

, script "run_at":"document_start" message. , event.stopImmediatePropagation(). (, ).

, DOM.
(i) , - , . , , DOM.

, A B:

  • script A:

    • (, , B).
  • :

  • script A:

    • R .
    • postMessage B R.
  • script B:

    • R A.
    • , frameId (, , A).

. , . , .

+5

All Articles