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

后端 未结 1 1511
一个人的身影
一个人的身影 2021-01-27 05:28

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 tha

相关标签:
1条回答
  • 2021-01-27 06:12

    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.

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