从Chrome扩展程序访问iframe URL

8
我有一个扩展程序,需要在其背景页面中加载许多重定向的页面。一旦该页面到达已知的URL (https://website.com/index.php),则应将iframe的 src 设置为 about:blank 。
最终页面非常大,具有不需要加载的大型图像和其他内容,因此我没有依附于iframe的 onload 事件,而是在100毫秒间隔上设置了以下函数:
function update(){
    if(document.getElementsByTagName('iframe')[0].contentDocument.location.href == "https://website.com/index.php"){
        console.log("Done!");
        clearInterval(updateInterval);
        document.getElementsByTagName('iframe')[0].src = "about:blank";
    }
}

然而,一旦iframe开始加载,update()就会抛出以下错误:

Unsafe JavaScript attempt to access frame with URL https://website.com/index.php from frame with URL chrome-extension://hdmnoclbamhajcoblymcnloeoedkhfon/background.html. The frame requesting access has a protocol of 'chrome-extension', the frame being accessed has a protocol of 'https'. Protocols must match.

我尝试使用catch()捕获该错误,但是传递回JavaScript的消息不包括URL,这并不奇怪。页面会多次重定向,因此知道确切的URL非常重要。iframe的src属性也不会更新以反映重定向。
1个回答

10

在经过大量谷歌搜索并且几乎放弃之后,我想出了以下解决方案。它使用注入的内容脚本,在正确的页面加载后向扩展程序发送一条消息。

manifest.json:

{
    ...
    "background": {
        "page": "background.html"
    }, "content_scripts": [
        {
            "matches": ["http://website.com/index.php"],
            "js": ["content.js"],
            "all_frames": true,
            "run_at": "document_start"
        }
    ],
    "permissions": [
        "*://*.website.com/*"
    ]
}

background.html:

<html>
    <head>
        <script type="text/javascript" src="background.js"></script>
    </head>
    <body>
        <iframe src="about:blank"></iframe>
    </body>
</html>

后台脚本.js:

var waiting = false;

function login(){ // Call this function to start
    var frame = document.getElementsByTagName('iframe')[0];
    frame.src = "https://website.com/login/";
    waiting = true;
}

function callback(){ // This gets called once the page loads
    console.log("Done!");
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    if(request.loaded && waiting){
        // If you used a pattern, do extra checks here:
        // if(request.loaded == "https://website.com/index.php")
        document.getElementsByTagName('iframe')[0].src = "about:blank";
        waiting = false;
        callback();
    }
});

内容.js:

chrome.extension.sendMessage({loaded: window.location.href});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接