尝试制作一个简单的Chrome扩展程序,用于跟踪您在网页上停留的时间。我一直遇到很多麻烦。当我运行扩展时,调试器会经历一个循环,说它无法设置null的innerhtml
,因为它无法找到id为elapsedTime
的元素。在调试器中,当我检查文档时,元素不在那里。我认为这与未点击图标时未加载的html有关,但我不确定如何处理这个问题。但是无论哪种方式!任何帮助表示赞赏。
background.js,manifest.json和index.html
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if (tab.status == 'complete') {
let startDate = new Date();
let elapsedTime = 0;
setInterval(function() {
timeNow = new Date();
elapsedTime = timeNow - startDate;
document.getElementById('elapsedTime').innerHTML = elapsedTime;
},100);
};
});

{
"name": "Timer-Extension",
"description": "A timer that displays how long you have been on a page",
"version": "0.1",
"manifest_version": 2,
"browser_action": {
"default_icon": "src/img/clock-16.png",
"default_popup": "src/index.html",
"default_title": "Timer-Extension"
},
"icons": {
"16": "src/img/clock-16.png",
"48": "src/img/clock-48.png",
"128": "src/img/clock-128.png"
},
"permissions": [
"tabs"
],
"background": {
"scripts": ["src/js/background.js"]
}
}

<html>
<body>
<p id = 'elapsedTime'></p>
<script type='text/javascript' src = js/background.js></script>
</body>
</html>
&#13;