javascript - 如何使用存储将数据从 options.js 发送到 content.js?
问题描述
我是一名 JavaScript 初学者,对于我的第一个项目,我认为我会编写一个有用的 chrome 扩展,但是,我一直坚持如何将数据从我的 chrome 扩展选项页面发送到正在运行该页面的 javascript。
在options.js
. 我已经成功地使用以下方法从存储中添加和检索值:
chrome.storage.local.set(obj)
chrome.storage.local.get(obj)
只要我在同一个 js 文件中存储和检索,它就可以正常工作 - options.js
。
我复制了从options.js
into检索值的相同块content.js
,但是该值始终显示为undefined
chrome 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;
});
}
任何有关如何进行的建议将不胜感激。
解决方案
谢谢@wOxxOm,我现在明白这是一个异步调用,这就是为什么这不起作用:
function getValue(textboxId) {
storage.get(textboxId, function(result) {
return result.name; << this is the problem
});
}
推荐阅读
- magento - Magento 1.9:Checkout Validate 方法重复调用里面的代码
- c++ - 为 Qt 项目树中的所有项目定义一个全局宏
- ios - 如何使用 mvvm 在 tableviewsection 中显示数据
- c - 分配超出范围的值时,静态分配的数组不会溢出
- php - 如何调试错误“已弃用:curl_setopt():”
- typescript - 打字稿是类型检查不包含的文件吗?
- tcl - tcl 脚本中的命令名无效
- c - 以结构为输入参数的 C 代码的 FMU 导出
- oracle - pl/sql 函数中的多个查询
- data-structures - 如何在不需要分配新变量的情况下为链表实现前置?