【发布时间】:2020-02-03 05:32:31
【问题描述】:
我有一个在 Option.html 文件中声明并保存到 Option.js 中的 chrome 存储的元素。我想访问该元素的值,以便可以在我的 Content.js 中使用它。有什么可能的方法吗?
我尝试在 Content.js 中通过其 ID 调用该元素,但它不起作用!它给出“Cannot read property 'value' of null”,所以我假设它没有读取元素(因为它不在同一个文件中)。
这是我所拥有的:
选项.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”值的方法,我将不胜感激! (或任何符合目的的替代解决方案)。
【问题讨论】:
-
选项页面是一个单独的页面,不能直接从内容脚本访问。您可以做的是使用 chrome.storage.local 将值保存在选项页面中并读取内容脚本中的值。您已经保存了值,现在只需读取它: chrome.storage.sync.get({favoriteColor: 100}, data => { var timeout = data.favoriteColor; /* 在回调中使用超时 */ })跨度>
标签: javascript dom google-chrome-extension