chrome.storage.local.get 和 set [英] chrome.storage.local.get and set

查看:80
本文介绍了chrome.storage.local.get 和 set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的扩展程序中使用 chrome.storage.local,但它似乎不起作用.我使用了 localStorage,但意识到我不能在多个页面的内容脚本中使用它.

I'm trying to use chrome.storage.local in my extension, and it doesn't seem to work. I used localStorage but realized that I can't use it in content scripts over multiple pages.

所以,这就是我想出的:

So, this is what I've come up with:

function save()
{
    var channels = $("#channels").val();
    var keywords = $("#keywords").val();

    chrome.storage.local.set({'channels': channels});
    chrome.storage.local.set({'keywords': keywords});
}

我相信我的 save() 是正确的,但问题出现在 load() 中:

I do believe I'm doing the save() right, but the problem comes up in load():

function load()
{
    var channels = "";
    chrome.storage.local.get('channels', function(result){
        channels = result;
        alert(result);
    });

    var keywords = "";
    chrome.storage.local.get('keywords', function(result){
        keywords = result;
        alert(result);
    });

    $("#channels").val(channels);
    $("#keywords").val(keywords);
}

当警报触发时,它会打印出[object Object].这是为什么?我究竟做错了什么?我查看了文档/示例,但似乎无法确定问题所在.

When the alerts trigger, it prints out [object Object]. Why is that? What am I doing wrong? I looked at the documentation/examples, but I can't seem to pinpoint the problem.

推荐答案

这段代码对我有用:

function load() {
    var channels = "";
    var keywords = "";
    chrome.storage.local.get('channels', function (result) {
        channels = result.channels;
        alert(result.channels);
        $("#channels").val(channels);
    });
} 

Chrome.storage.local.get() 返回在键值映射中包含项的对象,因此您必须在搜索模式中使用键的索引.

Chrome.storage.local.get() returns an object with items in their key-value mappings, so you have to use the index of the key in your search pattern.

感谢 Rob 识别:Chrome.storage.local.get()异步,你应该修改您的代码以确保它们在 callback() 成功后工作.

Thanks to Rob for identifying: Chrome.storage.local.get() is asynchronous, you should modify your code to ensure they work after callback() is successful.

如果您需要更多信息,请告诉我.

Let me know if you need more information.

这篇关于chrome.storage.local.get 和 set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆