Chrome extension: store data on background

后端 未结 3 697
情书的邮戳
情书的邮戳 2021-02-04 19:21

I want to be able to store data on background (on my extension) so I can access this data between multiple domains.

Where\'s what I\'m doing:

content-scr

3条回答
  •  感情败类
    2021-02-04 20:07

    background-script.js:

    chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
        switch (request.command) {
            case 'setItem':
                localStorage[request.name] = JSON.stringify(request.data));
                return;
            case 'getItem':
                var retValue;
                if (typeof(localStorage[request.name]) === 'string') {
                    retValue = JSON.parse(localStorage[request.name]);
                }
                sendResponse(retValue);
                return;
            case 'deleteItem':
                if (typeof localStorage[request.name] !== 'undefined') {
                    delete localStorage[request.name];
                }
                return;
        }
    });
    

    If the key is not in the localStorage, getItem will return undefined. Instead of defining the function getItem the way you did, you should send a message to the background with a callback and then do something with the value when the callback is called. You can't return the value from the function getItem, but you can use the value in the callback when it is called:

    function getItem(name, callback) {
        chrome.extension.sendMessage({command: 'getItem', name: name}, function(response) {
            if (typeof(callback) === "function") {
                callback(response);
            }
        });
    }
    

提交回复
热议问题