Chrome扩展setInterval或setTimeout,因为页面加载速度太慢

问题描述:

我正在创建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,但我不工作。

我通过更改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' 
    }); 
    } 
}); 

创建background.js也放到了清单,而不是popup.js。

然后引用popup.js从popup.html与

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

这样popup.js可以访问popup.html DOM。

我认为这就是所有你需要做的,但没有时间去尝试。

+0

我应该把什么放入background.js? – mrblue