2013-03-26 61 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});