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

Hic*_*ick 11 javascript google-chrome-extension

这是我的问题:

我在一个新选项卡中更新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));
}
Run Code Online (Sandbox Code Playgroud)

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);

});
Run Code Online (Sandbox Code Playgroud)

Sud*_*han 14

后台浏览器操作(在您的情况下)页面位于隔离的世界中,彼此无法访问其本地存储详细信息,如果您希望此类访问发生,请使用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"]
}
Run Code Online (Sandbox Code Playgroud)

popup.html

一个简单的弹出式html页面,它引用popup.js超越CSP.

<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

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));
});
Run Code Online (Sandbox Code Playgroud)

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");
    });
});
Run Code Online (Sandbox Code Playgroud)

如果查看这些js页面的输出,就可以实现存储通信(后台 - >弹出窗口和弹出窗口 - >后台).