这是我的问题:
我在新选项卡中更新popup.js中的localStorage。我在background.js中访问相同的localStorage(相同的密钥)。
现在,除了chrome:// extensions选项卡之外,每个选项卡都返回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);
});
答案 0 :(得分:14)
Background和Browser Action(在您的情况下)页面生活在孤立的世界中,如果您希望使用{{3}这种类型的访问,则彼此无法访问其本地存储详细信息为了您的存储需求。
它没什么优势
chrome.storage.local.get
sync
代替local
确保所有权限都可用于访问存储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"]
}
一个简单的弹出式html页面,它引用popup.js超越CSP。
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
此脚本将内容设置为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));
});
此脚本检索并设置从\到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页面的输出,就可以实现存储(背景 - >弹出窗口和弹出窗口 - &gt;背景)的通信。