问题 LocalStorage在chrome中的不同选项卡中返回null


这是我的问题:

我在一个新选项卡中更新popup.js中的localStorage。我在background.js中访问相同的localStorage(相同的密钥)。

现在,除了chrome://扩展选项卡(当我加载扩展时),每个选项卡都会返回null。

我认为localStorage在所有标签中都是持久的。

码:

popup.js:

$(document).ready(function (){

    alert(localStorage.getItem('filters'));
    var oldFilters = localStorage.getItem('filters');
    //All the filters show up on the popup.html page.
    document.getElementById('td1').innerHTML = oldFilters;

    var dat = oldFilters + "," + newArray[j]
    localStorage.setItem('filters',String(dat));
}

background.js:

$(window).ready(function() {
  // Handler for .ready() called.

 var filters = localStorage.getItem('filters');

   alert("background + "+ filters);
    //This shows all the filters in the chrome:extensions page but always pops up "background + null" in every new tab load. 

//changeImage(filters);

});

1257
2017-12-23 04:21


起源

如果您在inspect元素中查看本地存储 - >资源是什么? - Brett Gregson
不。那里什么都没有。 - Hick
你确定它一直被设定吗? - Brett Gregson
当然,这就是流程。这就是为什么当我转到chrome:扩展页面并重新加载数据时,它会向我显示所有存储的数据。 - Hick
添加了popup.js和background.js的代码 - Hick


答案:


背景 和 浏览器操作(在您的情况下)页面生活在孤立的世界中,如果您希望这种访问发生使用,则它们的本地存储详细信息彼此无法访问 chrome.storage 满足您的存储需求。

它几乎没有什么优势

  • 您的扩展程序的内容脚本可以直接访问用户数据,而无需后台页面。
  • 即使使用拆分隐身行为,也可以保留用户的扩展程序设置。
  • 用户数据可以存储为对象(localStorage API将数据存储在字符串中)。

使用的方法

示范

的manifest.json

确保所有权限都可用于访问存储API。

{
"name":"Local Storage Demo",
"description":"This is a small use case for using local storage",
"version":"1",
"manifest_version":2,
"background":{
    "scripts":["background.js"]
},
"browser_action":{
    "default_popup":"popup.html",
    "default_icon":"logo.png"
},
"permissions":["storage"]
}

popup.html

一个简单的弹出式html页面,它引用popup.js超越CSP。

<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>

background.js

此脚本将内容设置为chrome存储

//Set some content from background page
chrome.storage.local.set({"identifier":"Some awesome Content"},function (){
    console.log("Storage Succesful");
});
//get all contents of chrome storage
chrome.storage.local.get(null,function (obj){
        console.log(JSON.stringify(obj));
});

popup.js

此脚本检索并设置从\到chrome存储的内容

document.addEventListener("DOMContentLoaded",function (){
    //Fetch all contents
    chrome.storage.local.get(null,function (obj){
        console.log(JSON.stringify(obj));
    });
    //Set some content from browser action
    chrome.storage.local.set({"anotherIdentifier":"Another awesome Content"},function (){
        console.log("Storage Succesful");
    });
});

如果你看看这些js页面的输出,存储的通信 (背景 - >弹出窗口和弹出窗口 - >背景) 已完成。


14
2017-12-23 06:54



很棒的答案。我在SO上尝试了很多解决方案,这让我再次相信美丽的人性!谢谢 - Jesse Smith