I’m writing a Manifest v3 Chrome extension that injects a content script into all frames of a tab. This content script needs to be able to pass a message from a parent frame to its subframes / iframes so that the iframes know where on the page they’re positioned.
I can have a background script use chrome.webNavigation.getAllFrames
in order to get all of the frames and determine what their hierarchy is, and then have the background script be an intermediary that allows the frames to pass messages between each other.
However, in order for an iframe to know where on the page it is, I need to be able to figure out which HTMLElement
instance in the DOM corresponds to a particular frame returned by chrome.webNavigation.getAllFrames
, and I’m not sure how to do it.
One method I found here involves using an iframe’s contentWindow
property. I can write a property on to the subframe’s window
whose value is the document ID returned by chrome.webNavigation.getAllFrames
, and then use an iframe’s contentWindow
proeprty to figure out which iframe has the matching document ID. But this fails if the iframe’s URL has a different domain than the parent frame, because cross-site scripting protections forbid the parent frame from reading that property.
The only other thing I can find is to use the URL of the iframe, since chrome.webNavigation.getAllFrames
includes that information. However, this will fail if more than one iframe in the document has the same URL.
Is there a way to do this?