In my Chrome extension I am injecting the content script into all IFRAMEs
inside a page. Here's a part of the manifest.json
file:
"content_scripts": [
{
"run_at": "document_end",
"all_frames" : true,
"match_about_blank": true,
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}
],
So a single web page having multiple IFRAMEs
will end up running that many copies of my injected content.js
.
The logic inside content.js
collects data from each IFRAME
it's injected into, or from the main/top page, and sends it back to the background script (using chrome.runtime.sendMessage
.) The background script in turn needs to store the data in the global variable, that is later used in the extension itself.
The issue I'm facing is that the app needs to distinguish between the "data" received from multiple IFRAMEs
, since my data collection method can be called repeatedly upon user's interaction with the page, and thus I cannot simply "dump" the data received by the background script into an array. Instead I need to use a dictionary
-type data storage.
I can tell if the data is coming from an IFRAME
or from the top page by running the following:
//From the `content.js`
var isIframe = window != window.top;
and my thinking was that if I collect page URLs of each IFRAME
then I should be able to use it as a unique key to store the data under in my dictionary-type global variable:
//Again from content.js
var strUniqueIFrameURL = document.URL;
Well, that is not going to work, because two or more IFRAMEs
can have the same URLs.
So thus my original question -- how to tell IFRAMEs
on the page apart? Is there some unique ID or somethign that Chrome assigns to them?
<iframe>
s on it, content scripts are injected in all of them, and you want to know "this is the content script in 2nd<iframe>
on tab X". And iframes are cross-origin to make it more fun. Am I understanding correctly? If yes, it's an interesting question. – Fungicideiframes
can be both same- and cross-origin. (I am not the author of the pages that my content script is injected into, so I'm assuming both scenarios.) – Sunlesswindow.frameElement
andwindow.parent.document.querySelectorAll("iframe")
. But you can't access those with cross-origin iframes. – Fungicidewindow.parent
, unlike frame's own code. – Fungicide