我有Chrome扩展程序我正在尝试使用启用/禁用选项添加功能。
我在popup.html中有复选框onclick,将框的值写入localStorage。然后在我的内容脚本中,我发送了一个值的请求。
我过去只有1个请求,而且运行正常。然后我尝试添加另一个,无论我尝试什么,它都不起作用,即使我注释掉其他请求。这是我的内容脚本中的代码:
autopoke = 'default';
secondbutton = 'default';
chrome.extension.sendRequest({localstorage: "autopoke"}, function(response)
{
if (response.autopoke == "true")
{
autopoke = true;
}
})
chrome.extension.sendRequest({localstorage: "secondbutton"}, function(response)
{
console.log(response) //for debugging
if (response.secondbutton == "true")
{
secondbutton = true;
}
})
无论“secondbutton”localStorage变量是否为true,第二个请求的输出都是空白。 Chrome控制台的输出也是一个空白对象。我尝试将该行移动到第一个请求,并输出一个对象,其中某处是“autopoke = false”。
为确保设置了localStorage值,我将其添加到popup.html:
alert(localStorage.secondbutton);
当我点击弹出窗口时,会出现一条提示 true 的警告。我真的无法弄清楚这一点,我甚至尝试了setTimeout()等待几秒钟,但结果是一样的:localStorage“secondbutton”的空白输出。
background.html:
<html>
<script type='text/javascript'>
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.localstorage == "autopoke") {
sendResponse({autopoke: localStorage.autopoke});
}
else {
sendResponse({}); // snub them.
}
});
</script>
</html>
popup.html:
<html>
<head>
<style type='text/css'>
body
{
font-size:10pt;
width:220px;
font-family: "Verdana";
font-weight: bold;
text-shadow: 2px 2px 2px green;
}
</style>
<script type='text/javascript'>
function update()
{
localStorage.autopoke = document.myform.check.checked;
localStorage.secondbutton = document.myform.secondbutton.checked;
}
</script>
</head>
<body>
<form name='myform'>
<table border="0">
<tr>
<td>
<label for='check'>Autopoke:</label>
</td>
<td>
<input type='checkbox' id='check' onclick='update()'/>
</td>
</tr>
<tr>
<td>
<label for='secondbutton'>Additional Poke Button:</label>
</td>
<td>
<input type='checkbox' id='secondbutton' onclick='update()'/>
</td>
</tr>
</table>
</form>
<script type='text/javascript'>
if( localStorage.autopoke == "true")
{
document.myform.check.checked=true;
}
if ( localStorage.secondbutton == "true" )
{
document.myform.secondbutton.checked=true;
}
</script>
</body>
</html>
答案 0 :(得分:1)
好的,让我们看看这里发生了什么。您首先使用localstorage = "autopoke"
发送请求。请求处理程序中的if语句保持并发回localStorage.autopoke
值。现在,当你发送localstorage = "secondbutton"
时,为什么它没有回应?好吧,代码中没有返回值的地方。尝试下面的代码,它应该可以解决问题。
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
if (request.localstorage == "autopoke")
{
sendResponse({autopoke: localStorage.autopoke});
}
else if (request.localstorage == "secondbutton")
{
sendResponse({secondbutton: localStorage.secondbutton});
}
else
{
sendResponse({}); // snub them.
}
});