簡體   English   中英

從Chrome擴展程序訪問iframe中的DOM元素

[英]Access DOM elements inside iframe from chrome extension

有沒有辦法在iframe中訪問DOM元素而不會出現跨域錯誤?
基本上,我希望能夠點擊擴展程序中位於iframe內的按鈕來啟動視頻。

我真的不知道該如何進行,我嘗試了iframe.contentDocument但收到了跨域錯誤。

background.js:

chrome.tabs.executeScript({
    "file": "script.js",
    "allFrames" : true
});

script.js

var iframe = document.getElementById("iframeId");
var button = iframe.contentDocument.getElementsById("buttonId");

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

謝謝

蠻力:將腳本插入iframe

如果您在訪問iframe的內容時遇到問題,則蠻力方法是將內容腳本直接注入iframe並從該內容腳本訪問iframe。

注入一個框架:
您可以通過在調用chrome.tabs.executeScript()提供幀ID來顯式指定將腳本注入的幀。 可能是這樣的:

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

如果您不知道要注入的幀的幀ID,則可以從chrome.webNavigation.getAllFrames()獲取它,例如:

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

注入所有幀:
如果要注入選項卡中的所有框架,則可以執行已在“問題”中顯示的操作:

chrome.tabs.executeScript({
    "file": "script.js",
    "allFrames" : true
});

這會將script.js文件注入到當前窗口的活動選項卡中所有在執行tabs.executeScript()調用時存在的tabs.executeScript() 將在選項卡的每個框架(包括基礎框架)中注入不同的script.js副本。 在調用tabs.executeScript()之后,這不會在添加到選項卡的任何iframe中注入script.js 對於iframe,注入的腳本所在的上下文將一直有效(即腳本將存在),直到iframe的URL更改(例如src屬性更改)或父框架(例如選項卡的基礎框架)更改為止URL(即在父框架中加載了新頁面)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM