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. 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.
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. 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.
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);
}
);
精彩评论