LocalStorage在chrome中的不同选项卡返回null
LocalStorage returning null in a different tab in chrome
这是我的问题:
我在一个新的选项卡中更新了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)的通信是实现的
相关文章:
- 为什么数据列表选项的id返回空值
- 引导选项卡不适用于历史记录.返回选项
- 在 jquery 选项卡中查找 span 标记并返回该索引
- 选择选项的值将在表单上返回 erro 时丢失
- 当我点击浏览器返回选项时,阻止在php上刷新页面
- 辅助功能键盘专用选项卡到z索引“;返回顶部”;
- 使用jquery取消隐藏或返回多选时的选定选项
- 引导程序3:返回页面刷新的下拉选项卡
- 自定义Div滑块运行过快,但仅当从另一个浏览器选项卡返回时
- Appcelerator 中的自定义选项卡栏 - 如何返回到根窗口
- 纯 JS 获取所选选项数据属性值返回 Null
- select2 - 如果多个选项共享一个值,则返回不正确的选定选项
- 函数,使用 React 返回带有选项的选择
- 自定义车把.js助手不返回选项.fn
- 如何在 asp.net 中使用角度选项卡返回上一页
- 当选项卡加载火狐插件SDK时返回函数
- 锤子.js 2.0 使用 jquery 插件时不返回事件选项
- 对多个选项进行筛选数组以在新选择中返回选项
- 如何从angularjs指令中的ng选项返回对象的索引
- Bookshelf js fetch withRelated选项返回空关系对象