Is Local Storage Persistant?

限于喜欢 提交于 2019-12-25 02:20:00

问题


I'm using Local Storage for a Chrome extensions. When I set the local storage using

localStorage['tracking'] = false;

... and then check to is local storage set using:

if(localStorage['tracking'])
{
    alert('set');
} else {
    alert('Not Set');
    localStorage['tracking'] = true;
}

It works fine. It sets tracking to true if unset and remains set. But if I go to a new tab, and to the same page I was on in the other tab, it returns unset.

Is there any way for local storage to remain persistant, even after the browser has closed?

Edit: I am not setting the localStorage array element at the top if the script. Just realised that might confuse readers.


回答1:


Try:

localStorage.setItem('tracking', false);

and

localStorage.getItem('tracking');

These are the methods used in the W3C API Specification.

Since the usage you mentioned is not specified, depending on browser implementation it is possible that you are adding new properties to the localStorage global variable in the current window object, which become unavailable when navigating away from the page.




回答2:


LocalStorage works only with strings. Check this explanation.




回答3:


I used to have the same problem. I would like to share my solution. However, my case may not be the same as your case.

My case ist that I had this code (localStrage['xxxx']='xxx';) in a content script. Then I had the problem when open the new tab or open new windows.

So, my solution is that I did not run this code by the content script directly. The content script will call 'chrome.extension.sendRequest' and the background.html will do set/read localStrage and return to the content script.

This will be the code in content script

chrome.extension.sendRequest({action: 'load'}, function (response) {
            if(response){
                  alert('set');
            } else {
                  alert('Not Set');
                  chrome.extension.sendRequest({action: 'set',value:'true'}, function (response) {});
            }
}

This will be the code in background.html.

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    if (request.action == 'load') {
        sendResponse(localStorage['tracking']);

            }else if (request.action == 'set') {
                localStorage['tracking']=request.value;
            }
     });


来源:https://stackoverflow.com/questions/8200646/is-local-storage-persistant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!