从 chrome 扩展访问 iframe 内的 DOM 元素

Dav*_*ssi 3 javascript iframe google-chrome google-chrome-extension

有没有办法访问 iframe 内的 DOM 元素而不会出现跨域错误?
基本上,我希望能够单击 iframe 内的按钮以从我的扩展程序启动视频。

我真的不知道如何继续,我已经尝试过,iframe.contentDocument但出现跨域错误。

背景.js:

chrome.tabs.executeScript({
    "file": "script.js",
    "allFrames" : true
});
Run Code Online (Sandbox Code Playgroud)

脚本.js

var iframe = document.getElementById("iframeId");
var button = iframe.contentDocument.getElementsById("buttonId");
Run Code Online (Sandbox Code Playgroud)

我得到的错误:
Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://website.com" from accessing a cross-origin frame.

谢谢

Mak*_*yen 6

蛮力:在 iframe 中注入脚本

如果您在访问 iframe 的内容时遇到问题,那么暴力方法是将内容脚本直接注入 iframe 并从该内容脚本访问 iframe。

注入单个帧:
您可以通过在调用chrome.tabs.executeScript(). 这可能是这样的:

chrome.tabs.executeScript(tabOfInterestId,{
    frameId: frameIdToInject,
    file: scriptFileWhichDoesWhatIWantInTheIframe.js
},function(results){
    //Handle any results
});
Run Code Online (Sandbox Code Playgroud)

如果您不知道要注入的帧的帧 ID,可以从以下位置获取chrome.webNavigation.getAllFrames()

chrome.webNavigation.getAllFrames({tabId:tabOfInterestId},function(frames){
    //Do what you want with the array of frame descriptor Objects
});
Run Code Online (Sandbox Code Playgroud)

注入所有框架:
如果你想注入一个选项卡中的所有框架,你可以做你在问题中显示的你已经在做的事情:

chrome.tabs.executeScript({
    "file": "script.js",
    "allFrames" : true
});
Run Code Online (Sandbox Code Playgroud)

这会将script.js文件注入到当前窗口的活动选项卡内的所有框架中,这些框架在执行调用时存在tabs.executeScript()。将在选项卡内的每个框架中注入不同的script.js副本,包括基础框架。这不会在调用后添加到选项卡的任何 iframe 中注入script.jstabs.executeScript()。对于 iframe,注入脚本所在的上下文将有效(即脚本将存在),直到 iframe 的 URL 更改(例如src属性更改),或父框架(例如选项卡的基本框架)更改 URL (即在父框架中加载了一个新页面)。