LocalStorage returning null in a different tab in chrome

后端 未结 1 786
不知归路
不知归路 2020-12-13 22:25

This is my issue:

I update the localStorage in popup.js in a new tab. I access the same localStorage(same key) in the background.js.

Now this is returning n

相关标签:
1条回答
  • 2020-12-13 23:30

    Background and Browser Action(In your case) Pages live in isolated worlds, their local storage details are not accessible to each other, if you want this sort of access to happen use chrome.storage for your storage needs.

    It has few advantages

    • Your extension's content scripts can directly access user data without the need for a background page.
    • A user's extension settings can be persisted even when using split incognito behavior.
    • User data can be stored as objects (the localStorage API stores data in strings).

    Methods used

    • chrome.storage.local.get
    • chrome.storage.local.set
      (use sync instead of local if the data needs to be synchronized with Google Sync)

    Demonstration

    manifest.json

    Ensure all permissions are available for accessing storage 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

    A trivial popup html page which refers popup.js to surpass CSP.

    <!doctype html>
    <html>
    <head>
    <script src="popup.js"></script>
    </head>
    <body>
    </body>
    </html>
    

    background.js

    This scripts sets content to chrome storage

    //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

    This script retrieves and sets content from\to chrome storage

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

    If you look at outputs of these js pages, communication of storage (Background -> popup and popup -> background) is achieved.

    0 讨论(0)
提交回复
热议问题