我正在开发 Google Chrome 扩展程序,但遇到了一个相当奇怪的问题。(我会尽量保持简单)
基本上,我允许用户自定义setInterval
循环的间隔速度。我使用输入框执行此操作,当输入数据时,该输入框localStorage
在keyUp
. 然后该localStorage
值通过 Chrome 的消息传递 API 传递给内容脚本,setInterval
循环自动获取它。
选项.html
<!DOCTYPE html>
<head>
</head>
<body>
<input type="text" id="customTime_Input" onKeyUp="setPref_customTime()" />
<!--Call JavaScript functions after all elements are created-->
<script type="text/javascript" src="messagePassing.js"></script>
<script type="text/javascript" src="options.js"></script>
</body>
</html>
背景.html
<!DOCTYPE html>
<head>
<script type="text/javascript" src="messagePassing.js"></script>
<script type="text/javascript" src="content.js"></script>
</head>
<body>
</body>
</html>
消息传递.js
if(localStorage["scanTime"] == undefined || localStorage["scanTime"] == ""){
localStorage["scanTime"] = 2000;
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.method == "getScanTime"){
sendResponse({data: localStorage["scanTime"]});
console.log("scanTime LS, response: " + localStorage["scanTime"]);
}
}
);
选项.js
function setPref_customTime(){
var inputBoxElement = document.getElementById("customTime_Input");
localStorage["scanTime"] = inputBoxElement.value;
console.log("scanTime LS, setPref_customTime(): " + localStorage["scanTime"]);
}
内容.js
window.load = passMessages();
function passMessages(){
chrome.extension.sendRequest({method: "getScanTime"}, function(response) {
localStorage["scanTime"] = response.data;
console.log("scanTime LS, request: " + localStorage["scanTime"]);
});
scanPage();
}
function scanPage(){
console.log("scanTime LS, scanPage: " + localStorage["scanTime"]);
setInterval(function match(){
console.log("scanTime LS, match: " + localStorage["scanTime"]);
}, localStorage["scanTime"]);
}
并且控制台在输入自定义值后返回这些日志(当加载默认值时,它会为所有日志返回“2000”,就像它应该的那样):
scanTime LS, scanPage: 2000
scanTime LS, scanPage: 2000
scanTime LS, request: 5000
scanTime LS, request: 5000
scanTime LS, scanPage: 2000
scanTime LS, request: 5000
scanTime LS, match: 5000
scanTime LS, match: 5000
scanTime LS, match: 5000
scanTime LS, match: 5000
[etc]
它清楚地表明setInterval
正在使用新值,但页面和日志以旧值的速度刷新(这不是用户错误。我多次使用了截然不同的值并且得到了相同的结果)。localStorage
同名的 a 怎么能相隔几行有不同的值?
更新:我刚刚注意到控制台报告了console.log()
除“scanTime LS, response:”之外的所有命令。这很重要吗?