Chrome extension regarding injected script + localstorage

纵然是瞬间 提交于 2019-11-28 14:29:45
Rob W

First of all: You do not need an injected script to access the page's DOM (<img> elements). The DOM is already available to the content script.

Content scripts cannot directly access the localStorage of the extension's process, you need to implement a communication channel between the background page and the content script in order to achieve this. Fortunately, Chrome offers a simple message passing API for this purpose.

I suggest to use the chrome.storage API instead of localStorage. The advantage of chrome.storage is that it's available to content scripts, which allows you to read/set values without a background page. Currently, your code looks quite manageable, so switching from the synchronous localStorage to the asynchronous chrome.storage API is doable.

Regardless of your choice, the content script's code has to read/write the preferences asynchronously:

// Example of preference name, used in the following two content script examples
var key = 'adurl';

// Example using message passing:
chrome.extension.sendMessage({type:'getPref',key:key}, function(result) {
    // Do something with result
});
// Example using chrome.storage:
chrome.storage.local.get(key, function(items) {
    var result = items[key];
    // Do something with result
});

As you can see, there's hardly any difference between the two. However, to get the first to work, you also have to add more logic to the background page:

// Background page
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.type === 'getPref') {
        var result = localStorage.getItem(message.key);
        sendResponse(result);
    }
});

On the other hand, if you want to switch to chrome.storage, the logic in your options page has to be slightly rewritten, because the current code (using localStorage) is synchronous, while chrome.storage is asynchronous:

// Options page
function load_options() {
   chrome.storage.local.get('repl_adurl', function(items) {
       var repl_adurl = items.repl_adurl;
       default_img.src = repl_adurl;
       tf_default_ad.value = repl_adurl;
   });
}
function save_options() {
   var tf_ad = document.getElementById('tf_default_ad');
   chrome.storage.local.set({
       repl_adurl: tf_ad.value
   });
}

Documentation

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