首页 > 解决方案 > 如何使用存储将数据从 options.js 发送到 content.js?

问题描述

我是一名 JavaScript 初学者,对于我的第一个项目,我认为我会编写一个有用的 chrome 扩展,但是,我一直坚持如何将数据从我的 chrome 扩展选项页面发送到正在运行该页面的 javascript。

options.js. 我已经成功地使用以下方法从存储中添加和检索值:
chrome.storage.local.set(obj)
chrome.storage.local.get(obj)
只要我在同一个 js 文件中存储和检索,它就可以正常工作 - options.js

我复制了从options.jsinto检索值的相同块content.js,但是该值始终显示为undefinedchrome js 调试器中的值。对于我的生活,我不知道如何设置值options.js并在content.js

我做错了什么?能不能不跑chrome.storage.local.set(obj)进去options.js再跑chrome.storage.local.get(obj)进去content.js拉价值?

这是一个代码片段,向您展示我在做什么:

文本框 id 是name, in options.js

function saveTextbox(txtboxId) {
  var theValue = document.getElementById(txtboxId).value;
  var obj = {};
  obj[txtboxId] = theValue;
  storage.set(obj);
}


content.js

function getValue(textboxId) {
  storage.get(textboxId, function(result) {
    return result.name;
  });
}

任何有关如何进行的建议将不胜感激。

标签: javascriptgoogle-chrome-extensionlocal-storage

解决方案


谢谢@wOxxOm,我现在明白这是一个异步调用,这就是为什么这不起作用:

function getValue(textboxId) {
  storage.get(textboxId, function(result) {
    return result.name; << this is the problem
  });
}

推荐阅读