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

LocalStorage returning null in a different tab in chrome

本文关键字:选项 返回 null chrome LocalStorage      更新时间:2023-09-26

这是我的问题:

我在一个新的选项卡中更新了popup.js中的localStorage。我在后台访问相同的localStorage(相同的键)。

现在这是返回空在每个选项卡除了chrome://扩展选项卡(当我加载扩展。)

我认为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);
});

背景和浏览器动作(在你的情况下)页面生活在孤立的世界,他们的本地存储细节是不可访问的,如果你想要这种访问发生使用chrome。存储满足您的存储需求。

它几乎没有什么优点

  • 你的扩展的内容脚本可以直接访问用户数据,而不需要一个背景页面。
  • 即使使用分割隐身行为,用户的扩展设置也可以保持。
  • 用户数据可以存储为对象(localStorage API以字符串形式存储数据)。

方法

  • chrome.storage.local.get
  • chrome.storage.local.set
    (使用sync代替local,如果数据需要与谷歌同步)

示范

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页面的输出,存储(Background -> popup和popup -> Background)的通信是实现的