且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序关于注入脚本+本地存储

更新时间:2023-12-05 11:49:28

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