【问题标题】:Chrome extension: store data on backgroundChrome 扩展:在后台存储数据
【发布时间】:2012-06-29 15:11:51
【问题描述】:

我希望能够在后台(在我的扩展程序上)存储数据,以便我可以在多个域之间访问这些数据。

我在做什么:

content-script.js

function setItem(name, data) {
    chrome.extension.sendMessage({ command: 'setItem', name: name, data: data });
}

function getItem(name) {
    chrome.extension.sendMessage({ command: 'getItem', name: name }, function(response) {
        return response;
    });
}

background-script.js

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch (request.command) {
        case 'setItem':
            localStorage.setObject(request.name, request.data);
            return;
        case 'getItem':
            sendResponse(localStorage.getObject(request.name));
            return;
    }
});

但没有成功,因为我无法从 getItem 的回调内部返回。

我确实在 function(response) { } 回调中获取了数据,但我无法将其作为 getItem 的返回返回。

我应该怎么做?

【问题讨论】:

    标签: javascript google-chrome-extension local-storage


    【解决方案1】:

    内容.js

    var someVar = "hey hey!";
    
    chrome.extension.sendRequest({method: "fromContentScript",greeting: someVar}, function(response) {
    
        console.log(response.data); // response back from BG
    
        if(response.who == 'bg'){ // checks if the response is from BG
                //Something happened ...
        }
    
        var responseFromBg = response.data; // the response incase we need to use the message sent back... in this case should be 'hey yourself'
    
    
    });
    

    Background.js

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      // From content script.
      if (sender.tab) {
        if (request.method == "fromContentScript"){
    
            localStorage.setItem("welcome-message",request.greeting); // in this case there will now be a localStorage variable called 'welcome-message' set with the value of 'hey hey!'. This will be viewable in the chrome:extensions page, click on the 'background.html / generated background.html' then view the 'Development Tools' or in Windows hit 'CTRL + SHIFT + I' and look at the 'LocalStorage' tab...
    
          sendResponse({who: "bg",data: "hey yourself"}); // this is the response sent back, 'who' tells the content page where is responding, so it can do something with the response if needed.
            }else{
          sendResponse({}); // snub them.
            }
      }
    });
    

    Manifest.json // 以防这是您遇到的清单问题...这是我的大部分内容..

    {
      "name": "Name here",
      "version": "1",
      "manifest_version": 2,
      "description": "Enter desc here.",  
        "browser_action": {
        "default_icon": "img/icon16.png",
        "default_popup": "popup.html"
      },    
        "background": {
        "scripts": ["background.js"]
      },
      "permissions": [
        "tabs", "*://*/*"
      ],
        "icons": { "16": "img/icon16.png",
               "48": "img/icon48.png",
              "128": "img/icon128.png" },
      "content_scripts": [
        {
          "matches": ["*://*/*"],
          "js": ["js/jquery-1.7.2.min.js","content_script.js"],
          "run_at": "document_end"
        }
      ]
    }
    

    会用你的例子,但我今天早上很着急。我试图尽可能仔细地解释所有变量 - 抱歉:(

    【讨论】:

    • sendRequest 和 onRequest 已弃用
    • @Chris 我试过你的例子,但不幸的是不起作用,你能帮帮我吗:)
    • 第一次我不知道在哪里可以看到我创建的database,第二次我使用了你的background jscontent js,但没有任何帮助
    • 您需要使用Extensions页面打开后台页面,然后F12并在'Resources'标签下查看Local Storage
    【解决方案2】:

    这个 2012 年的问题是为了获得最新答案而提出的。好吧,那么..

    现在正确的答案是使用chrome.storage API。它是一个可供扩展页面和内容脚本访问的 API,它提供异步存储。它需要"storage" 权限,但此权限不会产生警告。

    // Setting
    chrome.storage.local.set({key: data}, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(data) +
          ": " + chrome.runtime.lastError.message
        );
      }
    });
    
    // Getting
    chrome.storage.local.get("key", function(data) {
      // Do something with data.key
    });
    

    另请参阅文档的 Examples 部分。

    请注意,在任何一种情况下(这种方法或消息传递后台方法),您都不能创建一个返回结果的函数getData,因为调用是异步的。

    一些提示和技巧:

    1. 您可以通过将对象或数组作为查询传递来一次设置或获取多个值。您可以通过传递null 查询来读取所有值。

    2. 您可以为get() 操作提供默认值,以防没有为键存储值,方法是传递类似{key: defaultValue} 的查询

    3. 可以通过chrome.storage.onChanged 事件通知您对存储的所有更改。

    4. chrome.storage.local 服从"unlimitedStorage" 权限。

    5. chrome.storage.sync 会将值传播到登录到同一 Google 帐户的所有配置文件,如果为扩展启用了 Chrome 同步。但是,请记住 quotas

    6. 如果您绝对需要同步访问,您可以使用由chrome.storage 支持的本地缓存来伪造它。但是,有一些限制:在同步代码块中,您的缓存不会随着其他页面的更改而更新,并且您需要异步读取一次值以填充缓存。

    【讨论】:

    • 还要确保在保存对象时不要使用保留关键字,例如“历史”……在这方面浪费了太多时间。
    【解决方案3】:

    背景脚本.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;
        }
    });
    

    如果 key 不在 localStorage 中,getItem 将返回undefined。而不是像您那样定义函数getItem,您应该通过回调向后台发送一条消息,然后在调用回调时对该值执行一些操作。你不能从函数getItem返回值,但是你可以在调用时在回调中使用该值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多