2017-11-25 278 views
0

我正在創建Chrome擴展。下面是它如何工作:Chrome擴展setInterval或setTimeout,因爲頁面加載速度太慢

開放的擴展 - >在當前選項卡中加載新的一頁 - >此頁閱讀內容 - >插入這個內容爲擴展HTML代碼(popup.html)。 (OK) - >在當前選項卡中加載新頁面(OK) - >從此頁面讀取內容(?) - >將此內容插入擴展HTML代碼(popup.html)(不工作)。

但是當我關閉擴展,然後再次打開它的工作原理。 我認爲這是因爲頁面加載速度太慢,我需要在步驟3或4中設置超時或間隔。我試過setInterval和setTimeout函數,但失敗了。

這是我popup.html(我已經刪除了不必要的東西):

<!DOCTYPE html> 
<html> 
<head> 
<meta name="myName" content="empty"> 
</head> 
<body> 
page content 
</body> 
</html> 

popup.js:

// Inject the payload.js script into the current tab after the popout has loaded 
window.addEventListener('load', function (evt) { 
    chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, { 
     file: 'payload.js' 
    }); 
    chrome.tabs.update(null, {url:"https://mypage.com"});; 

}); 

// Listen to messages from the payload.js script and write to popout.html 
chrome.runtime.onMessage.addListener(function (message) { 
document.getElementsByName("myName")[0].setAttribute("content", message); 
}); 

payload.js:

// send the page title as a chrome message 
chrome.runtime.sendMessage(document.getElementsByTagName("META")[0].content); 

清單。 JSON:

{ 
    "manifest_version": 2, 

    "name": "MyName", 
    "description": "empty!", 
    "version": "0.2", 
    "author": "me", 

    "background": { 
     "scripts": ["popup.js"], 
     "persistent": true 
    }, 

    "icons": { "16": "icon_16.png", 
    "48": "icon_48.png", 
    "128": "icon_128.png" }, 

    "permissions": [ 
     "tabs", 
     "http://*/", 
     "https://*/" 
    ], 
    "browser_action": { 
     "default_icon": "icon.png", 
     "default_popup": "popup.html" 
    } 
} 

我試着申請setInterval(function(){ code; }, 500);到popup.js和/或payload.js,但我不工作。

回答

0

我通過更改popup.js來修復它。現在payload.js在tab完成後加載站點後加載。這是我的最後一個popup.js:

// Open https://mypage.com in current tab when popup has loaded 
window.addEventListener('load', function (evt) { 
    chrome.tabs.update(null, {url:"https://mypage.com"}); 

}); 

// Listen to messages from the payload.js script and write to popout.html 
chrome.runtime.onMessage.addListener(function (message) { 
document.getElementsByName("name")[0].value = message; 
}); 

// Inject the payload.js script into the current tab after mypage.com has loaded 
chrome.tabs.onUpdated.addListener(function (tabId , info) { 
    if (info.status === 'complete') { 
     chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, { 
     file: 'payload.js' 
    }); 
    } 
}); 
0

創建background.js也放到了清單,而不是popup.js。

然後引用popup.js從popup.html與

<script src="popup.js"></script> 

這樣popup.js可以訪問popup.html DOM。

我認爲這就是所有你需要做的,但沒有時間去嘗試。

+0

我應該把什麼放入background.js? – mrblue