Javascript 在chrome的另一个选项卡中返回null的LocalStorage
这是我的问题: 我在一个新选项卡中更新popup.js中的localStorage。我在background.js中访问相同的本地存储(相同的密钥) 现在,除了chrome://extensions 选项卡(当我加载扩展时。) 我认为localStorage在所有选项卡上都是持久的 代码: popup.js:Javascript 在chrome的另一个选项卡中返回null的LocalStorage,javascript,google-chrome-extension,Javascript,Google Chrome Extension,这是我的问题: 我在一个新选项卡中更新popup.js中的localStorage。我在background.js中访问相同的本地存储(相同的密钥) 现在,除了chrome://extensions 选项卡(当我加载扩展时。) 我认为localStorage在所有选项卡上都是持久的 代码: popup.js: $(document).ready(function (){ alert(localStorage.getItem('filters')); var oldFilters
$(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);
});
而且(在您的情况下)页面生活在孤立的世界中,如果您希望这种访问能够满足您的存储需求,则它们的本地存储详细信息彼此无法访问
它没有什么优势
- 扩展的内容脚本可以直接访问用户数据,而无需后台页面
- 即使在使用拆分匿名行为时,也可以保留用户的扩展设置
- 用户数据可以存储为对象(localStorage API以字符串形式存储数据)
(如果数据需要与Google sync同步,请使用
而不是sync
)local
{
"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>
popup.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));
});
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页面的输出,就会实现存储的通信(后台->弹出窗口和弹出窗口->后台)。如果您在inspect element->resources中查看本地存储,是否有任何内容?没有。那里什么都没有。你确定它曾经被设置过吗?当然,这就是流程。这就是为什么当我进入chrome:extensions页面并重新加载数据时,它会显示所有存储的数据。添加了popup.js和background.js的代码。我尝试了很多解决方案,这一个让我再次相信人性的美丽!谢谢