0

I have saved some user data on one page using localStorage.setItem. I am now trying to reopen the data in another tab, but it will not work. Code sample below:

popup.js

    localStorage.setItem("item", document.getElementById('item').value);
    localStorage.setItem("color", document.getElementById('color').value);
    alert(localStorage.getItem("item"))
    // "Test"

Search.js

var kws = localStorage.getItem("item");
var color = localStorage.getItem("color");
alert(kws)
// "null"

LocalStorage is supposed to work on a browser, so calling it from a different tab should not matter.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • What are the urls of each tab? – Evert Jun 12 '20 at 01:44
  • Are both scripts in the same domain? – Barmar Jun 12 '20 at 01:44
  • @Barmar I'm building a Chrome Extension so I am not sure –  Jun 12 '20 at 01:47
  • @Evert I am building a Chrome Extension so the extension has no URL –  Jun 12 '20 at 01:48
  • 4
    Each domain has its own local storage. You should probably be using `chrome.storage` in an extension. – Barmar Jun 12 '20 at 01:49
  • @Barmar Thank you. I have tried to use chrome storage and I have run into another issue. popup.js ``` chrome.storage.sync.set({'item': document.getElementById('item').value}) ``` search.js ``` var keywords; chrome.storage.sync.get("kws", function(items){keywords = items.kws;}); alert(keywords) // undefined ``` Why can't I get the data from Chrome storage? –  Jun 12 '20 at 02:09
  • 1
    @ArthurXu because chrome API is asynchronous it should be used inside the callback, see [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – wOxxOm Jun 12 '20 at 03:20

0 Answers0