简体   繁体   中英

Chrome Extension Local Storage Accessing From Multiple Places

My extension has a content script that captures some info from certain pages and saves them into local storage using the following:

localStorage[myVarName] = value;    

If I put the following into my content script, I have no problem retrieving the stored values:

myGottenVariable = localStorage[myVarName];

Elsewhere, my extension creates a new window using

 chrome.windows.create({url:LocalURL}}

The newly created window is the main UI for my extension. One of the things I want it to do is retrieve the stored value at "myVarName." However, it is undefined.

I assume that this has to do with how the localstorage is organized. I have an intuition that each extension has its own storage space for local storage and that the created window lacks access to the content script's storage space.

This intuition is confirmed by the fact that I have tried storing content locally from the newly created window, and it has no problem retrieving that content.

My question is, what is the simplest method of achieving my desired result? I get tripped up pretty quickly when dealing with a lot of the chrome extension API stuff: so the ideal option would be as clean and simple as possible. That's why I liked the syntax of:

localStorage[myVarName] = value;   

Is there some simple way of modifying this to allow easy access to the desired content? Are both pages actually in the same storage space, but at different places in that directory?

localStorage is isolated per domain, which means if the new window has different domain from the domain where you saved data, you won't get what you saved.

To achieve what you want, you could use chrome.storage . The chrome.storage is shared by background page/content scripts. For your case, you could save data in content scripts and retrieve it in the created window (via content scripts).

chrome.storage.local.set({ key: value });
chrome.storage.local.get(key, function (result) {
    console.log(result.key);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM