【发布时间】:2014-04-27 23:22:27
【问题描述】:
我正在开发一个 chrome 扩展程序,它必须显示在访问过的网站上花费的时间。我使用localStorage 存储持久信息(网址和花费的时间)。
目前,我无法在我的 div“main-stat”(而不是控制台)中显示 url。你有想法吗 ? 我肯定忘记了事情并犯了错误...... 这是我的不同文件。
我的 manifest.json
{
"manifest_version": 2,
"version": "0.1",
"browser_action": {
"default_popup": "popup.html"
},
"options_page": "/option/options.html",
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}],
"web_accessible_resources": ["contentscript.js"],
"permissions": ["storage", "tabs", "http://*/*", "https://*/*"]
}
我的 popup.html
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="stylesheet.css">
<script type="text/javascript" src="popup.js"></script>
<script type="text/javascript" src="clear.js"></script>
</head>
<body>
<!--=============STATS ===========-->
<div id="main-stats">
</div>
<!--=============Restart timer===========-->
<div id="main-bouton">
<div id="bouton1">
<a href="popup.html" id ="bouton">Restart timer</a>
</div>
</div>
</body>
</html>
我的 contentscript.js
var lastPing = +new Date();
function ping() {
chrome.runtime.sendMessage({
domain: location.host,
lastPing: lastPing
}, function() {
lastPing = +new Date();
console.log('Ping send');
});
}
setInterval(ping, 5000);
我的背景.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
var domain = request.domain;
var lastPing = request.lastPing;
var time_elapsed = localStorage.getItem(domain) || 0;
localStorage.setItem(domain, time_elapsed + (+new Date() - lastPing));
});
我的 popup.js
for (var key in localStorage) {
console.log(key, localStorage.getItem(key));
}
我的 clear.js
document.getElementById("bouton").addEventListener("click", function clear(){
localStorage.clear();
console.log("Stats have been restarted !");
}, false);
任何帮助将不胜感激。
【问题讨论】:
-
您确定要在正确的控制台中查找结果吗?你在使用“检查弹出窗口”吗?
-
是的,我使用这个控制台..我有以下错误:“Uncaught TypeError: undefined is not a function ping” contentscript.js l4
-
为什么要在弹出窗口中加载
contentscript.js和background.js? -
你将 clear.js 移到了头部,但是当它执行时 DOM 还没有准备好,
document.getElementById将会失败。您需要使用类似 jQuery 的$(document).ready或将该特定脚本移至文档末尾。 -
您还有问题吗,或者您的问题得到了解答?
标签: javascript google-chrome-extension local-storage