How could i achieve to access the data which where set on options page in the content script eg. in the google chrome extension

依然范特西╮ 提交于 2019-12-20 06:43:02

问题


I am setting some values at the option page. This is now working okay. But i am unable to access the data setted in the background.html or in the content script. I have read that something like this is possible with messaging but for me is the documentation a little bit hard to understand. If someone could point me out in the right direction it would be good. Example story> I am setting this value at the options page localStorage.setItem("somedata" , "true"); Then if i would access the same data on the page where the extension would be to run i get it like this:

localStorage.getItem("somedata");

And the value is null.


回答1:


Content scripts cannot directly read the localStorage values from the background page. If you wish to read localStorage key-value pairs, see this answer which provides an explanation plus code for achieving this: Accessing global object from content script in chrome extension

Although the previous method works, I recommend the chrome.storage API instead: This can be used by all extension pages. A huge difference between localStorage and chrome.storage is that chrome.storage is an asynchronous API.

Here's an example to illustrate the dfferences:

// synchronous localStorage
localStorage.setItem('keyname', 'value');
alert(localStorage.getItem('keyname'));

// asynchronous chrome.storage
chrome.storage.local.set({keyname: 'value'}, function() {
    chrome.storage.local.get('keyname', function(items) {
        alert(items.keyname);
    });
});

On the first sight, the chrome.storage API looks more convoluted. However, if you want to save data within an extension, it's the best way to do so. The localStorage approach takes much more code (see the answer I linked on top of this answer) to achieve the same functionality. And, it's also asynchronous.



来源:https://stackoverflow.com/questions/12876835/how-could-i-achieve-to-access-the-data-which-where-set-on-options-page-in-the-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!