2013-03-26 60 views
7

我有一个扩展需要在其背景页面中加载一个包含大量重定向的页面。一旦该页面到达已知的URL(https://website.com/index.php),iframe应将其src设置为about:blank访问来自Chrome扩展的iframe网址

的最后一页是相当大的,有大的图像和一切,不需要加载,因此而不是附加到iframe的onload事件,我设置以下功能在100ms的时间间隔:

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开始加载,更新()抛出这个错误:

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.

我试图赶上()荷兰国际集团的错误,但传回的Javascript消息令人吃惊不包括URL 。该页面会多次重定向,因此了解确切的网址非常重要。 iframe的src属性也不会更新以反映重定向。

回答

8

之后谷歌几乎放弃,我想出了以下解决方案。它使用注入的内容脚本在正确的页面加载后将消息发回给扩展。

的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> 

background.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(); 
    } 
}); 

content.js:

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