我有一个在Option.html文件中声明的元素,并已保存到Option.js的chrome存储中。我想访问该元素的值,以便可以在Content.js中使用它。有可能吗?
我尝试在Content.js中通过其ID调用该元素,但没有成功!它给出了“无法读取null的属性'值'”,因此我认为它没有读取元素(因为它不在同一文件中)。
这是我所拥有的:
Option.html:
<!DOCTYPE html>
<html>
<head><title>My Test Extension Options</title></head>
<body>
waiting time:
<select id="waitingTime">
<option value="oneMin">1 minute</option>
<option value="TwoMin">2 minutes</option>
<option value="FourMin">4 minutes</option>
<option value="FiveMin">5 minutes</option>
</select>
<div id="status"></div>
<button id="save">Save</button>
<script src="options.js"></script>
</body>
</html>
Option.js:
// Saves options to chrome.storage
function save_options() {
var color = document.getElementById('waitingTime').value;
chrome.storage.sync.set({
favoriteColor: waitingTime,
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
Content.js(在其中称为元素):
....
//the line I'm calling the element
var timeout = document.getElementById('waitingTime').value;
....
Manifest.json(我添加了选项和权限):
....
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["storage", "activeTab"],
"options_page": "options.html",
....
如果您能帮助我找到一种从content.js文件访问“ waitingTime”值的方法,我将不胜感激! (或用于此目的的其他替代解决方案)。
答案 0 :(得分:1)
您已将值从options
保存到Chrome存储中,因此现在您只需要从此处读取值即可。由于content script
和option
位于不同的上下文中,因此我们要做的就是找到这两个上下文可以连接的位置,在这种情况下为Chrome Storage
。像这样:
options.js
// Saves options to chrome.storage
function save_options() {
var color = document.getElementById('waitingTime').value;
chrome.storage.sync.set({
favoriteColor: waitingTime,
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
content-script.js
chrome.storage.sync.get('favoriteColor', function(result) {
if (result && result.favoriteColor) {
// You can use it here: result.favoriteColor
}
});
我想提到的一件事是chrome.storage.sync
和chrome.storage.local
,您可能已经知道,但以防万一。
chrome.storage.sync
,在您使用您的帐户登录以同步浏览数据的Chrome浏览器之间同步数据,该操作具有读/写limitation
chrome.storage.local
不会同步数据,基本上它只是将数据存储在安装了扩展程序的浏览器中。此函数有存储大小限制(只能存储最大5,242,880
个字节),您可以阅读this document来增加它。