这是我的问题:
我在一个新选项卡中更新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);
});
背景 和 浏览器操作(在您的情况下)页面生活在孤立的世界中,如果您希望这种访问发生使用,则它们的本地存储详细信息彼此无法访问 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页面的输出,存储的通信 (背景 - >弹出窗口和弹出窗口 - >背景) 已完成。