开发者

HTML5 Local Storage, how to pass variables?

开发者 https://www.devze.com 2023-02-22 05:16 出处:网络
Ok, here is my problem. I am writing a Chrome extension, it\'s almost done, but the problem is, for example:

Ok, here is my problem. I am writing a Chrome extension, it's almost done, but the problem is, for example:

[Page popup.html]

localStorage["code"] = "alert('Hello!');";

[File injection.js; which will be called everytime a page is loaded, content script I think]

localStorage["code"] = (localStorage["code"] != undefined) ? localStorage["code"] : "alert('Default!');";
eval(localStorage["code"]);

I have tried 2 methods, the first thing is to NOT OPEN THE POP UP, so that 开发者_如何学编程every page I load would run command alert("Default!"); and it works. Then I tried to load the popup first, and I realize that the variable localStorage["code"] is now up to the page I load, not to my extenstion anymore. In a quick explanation, in my extension, localStorage["code"] == "alert('Hello');"; but in http://google.com localStorage["code"] == ""; or in http://facebook.com localStorage["code"] == "";.

My question is, is there anyway to store localStorage["code"] from popup.html that injection.js can access?


Three are 2 kinds of local storages - one belongs to extension itself (can be accessed only from a background page, popup page or any page bundled into extension package), another one belongs to the site (can be accessed only from a content script).

So if you need to access local storage value that was set in a popup from a content script, you need to send a request to a background page, read the value there, and send it back to a content script. How to do that is explained in Message Passing doc.


Check this out :

Content-Script :

chrome.extension.sendRequest({ action : "getCode" }, function(response) {
    alert(response.getCode);
}); 

Background Page :

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
{   
    case "getCode":
        sendResponse({ getCode: localStorage['code'] });
    break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消