Is there a way to acces DOM elements inside an iframe without getting a cross-origin error ?
Basically I want to be able to click a button located inside an iframe to launch a video, from my extension.
I really don't know how to proceed, I have tried iframe.contentDocument
but I get the cross-origin error.
background.js:
chrome.tabs.executeScript({
"file": "script.js",
"allFrames" : true
});
script.js:
var iframe = document.getElementById("iframeId");
var button = iframe.contentDocument.getElementsById("buttonId");
The error I get :
Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://website.com" from accessing a cross-origin frame.
Thank you
If you are having trouble accessing the contents of an iframe, the brute force method to do so is to inject a content script directly into the iframe and access the iframe from that content script.
Inject into a single frame:
You can explicitly specify the frame into which your script is injected by providing the frame ID in your call to chrome.tabs.executeScript()
. This could be something like:
chrome.tabs.executeScript(tabOfInterestId,{
frameId: frameIdToInject,
file: scriptFileWhichDoesWhatIWantInTheIframe.js
},function(results){
//Handle any results
});
If you don't know the frame ID for the frame into which you desire to inject, you can obtain it from chrome.webNavigation.getAllFrames()
like:
chrome.webNavigation.getAllFrames({tabId:tabOfInterestId},function(frames){
//Do what you want with the array of frame descriptor Objects
});
Injecting into all frames:
If you want to inject into all frames in a tab, you can do what you show in the Question that you are already doing:
chrome.tabs.executeScript({
"file": "script.js",
"allFrames" : true
});
This will inject the script.js file into all frames within the active tab of the current window which exist at the time the tabs.executeScript()
call is executed. A different copy of script.js will be injected in each frame within the tab, including the base frame. This will not inject script.js in any iframes which are added to the tab after this call to tabs.executeScript()
is made. For iframes, the context in which the injected script exists will be valid (i.e. the script will exist) until the URL for the iframe changes (e.g. the src
attribute changes), or a parent frame (e.g. the base frame of the tab) changes URL (i.e. a new page is loaded in a parent frame).