[英]Can't use localStorage value in my Google Chrome extension
I have written a Chrome extension that adds a char counter to some input elements. 我编写了一个Chrome扩展,为一些输入元素添加了一个char计数器。 There is no UI for this, it just injects the char counting code if the user is on a specific page.
没有用户界面,如果用户在特定页面上,它只会注入字符计数代码。
There is a limit to how many chars should appear in the inputs. 输入中应出现多少个字符是有限制的。 I initially wrote it to just display the number of chars but then I decided it would be nice if the user could choose to see how many chars they have left instead.
我最初编写它只显示字符数,但后来我觉得如果用户可以选择查看它们剩下多少个字符会很好。 So I decided to create an options page.
所以我决定创建一个选项页面。
At some point in my options page I do this: 在我的选项页面的某个时刻,我这样做:
localStorage["count"] = count; // count is the string "countUp" or "countDown"
It turns out I can't access the localStorage of options.html from the contentscript.js so I reluctantly created a background.html page which listens to requests from the contentscript and returns the localStorage values that the content script asks for. 事实证明我无法从contentscript.js访问options.html的localStorage所以我不情愿地创建了一个background.html页面,它监听来自contentscript的请求并返回内容脚本要求的localStorage值。
In contentscript (simplified) 在内容中(简化)
var countOption;
chrome.extension.sendRequest(
{method: "localStorage", key: "count"},
function(response){
countOption = response.data;
console.log(countOption); // returns "countUp"
}
);
console.log(countOption); // returns undefined
if(countOption === "countUp") {
doSomething();
} else {
doSomethingElse();
}
Background page 背景页面
<script type="text/javascript">
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.method === "localStorage") {
sendResponse({data: localStorage[request.key]});
} else {
sendResponse({});
}
}
);
</script>
The problem is I can't assign a value to countOption
so that it is accessible in the scope of the rest of my script. 问题是我无法为
countOption
分配一个值,以便在我的其余脚本范围内可以访问它。 When I assign it in the chrome.extension.sendRequest
's response this
is the window object so I have tried declaring countOption
globally but it is still undefined
in the rest of my script. 当我在
chrome.extension.sendRequest
的响应中分配它时, this
是窗口对象,所以我尝试全局声明countOption
,但在我的其余脚本中仍未undefined
。
Can anyone see where I'm going wrong? 谁能看到我哪里出错了? Thanks.
谢谢。
Would something like this work? 会这样的吗?
function executeCount(countOption)
{
console.log(countOption); // returns undefined
if(countOption === "countUp") {
doSomething();
} else {
doSomethingElse();
}
}
chrome.extension.sendRequest(
{method: "localStorage", key: "count"},
function(response){
executeCount(response.data);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.