访问内容脚本和弹出窗口中使用的Chrome本地存储? [英] Access chrome local storage used in both content script and popup?

查看:62
本文介绍了访问内容脚本和弹出窗口中使用的Chrome本地存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计我的第一个chrome扩展程序,但是遇到了问题.

I'm designing my first chrome extension and have run into a problem.

在我的popups.js上,用户可以输入单词和定义,这些单词和定义保存为chrome存储中的数组:

On my popups.js users can enter words and definitions that are saved as an array in chrome storage:

function save()
{
     chrome.storage.local.set({'words': words});
    chrome.storage.local.set({'definitions': definitions});
}

然后我想像这样在我的内容脚本js中加载这些单词和定义:

I would like to then load these words and definitions in my content script js like so:

function load()
{
    //load words from local storage
    chrome.storage.local.get('words', function (result) {
    if (result.words != "null") words = result.words;
    });

    //load definitions
    chrome.storage.local.get('definitions', function (result) {
        if (result.definitions != "null") definitions = result.definitions;
    });
}

但是,它根本不会加载数据.我已确保在运行内容脚本之前已保存数据.

However it does not load the data at all. I have made sure the data is saved before the content script is run.

我已经研究了消息传递,但是并不太了解/知道这是否是正确的方法.

I have looked into messaging but don't really understand it / know if that's even the right way to do it.

帮助表示赞赏!

推荐答案

已解决!

我现在使用同步而不是本地:chrome.storage.sync

I now use sync instead of local: chrome.storage.sync

在我将"start()"放入其中之后,我也没有等待存储的加载:

also I wasn't waiting for the storage to be loaded in, after I put my "start()" inside:

function load()
{
    //load words from local storage
    chrome.storage.local.get('words', function (result) {
    if (result.words != "null") words = result.words;
    });

    //load definitions
    chrome.storage.local.get('definitions', function (result) {
        if (result.definitions != "null") definitions = result.definitions;

start()
    });
}

有效.

这篇关于访问内容脚本和弹出窗口中使用的Chrome本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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