簡體   English   中英

Chrome擴展程序setInterval或setTimeout,因為頁面加載太慢

[英]Chrome Extension setInterval or setTimeout because page loads too slow

我正在創建chrome擴展程序。 它的工作方式如下:

打開擴展名->在當前選項卡中加載新頁面->從此頁面中讀取內容->將此內容插入擴展名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);

manifest.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,但我無法正常工作。

創建一個background.js並將其放入清單而不是popup.js。

然后從popup.html參考popup.js與

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

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

我認為這就是您需要做的,但沒有時間嘗試。

我通過更改popup.js進行了修復。 現在,payload.js在選項卡中的加載站點完成后即已加載。 這是我最后的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'
    });
  }
});

暫無
暫無

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

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