如何调用在Chrome扩展程序的OPTION.html页面中声明的元素?

问题描述 投票:0回答:1

我有一个在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”值的方法,我将不胜感激! (或任何其他可以达到目的的解决方案)。

javascript dom google-chrome-extension
1个回答
0
投票

您已将options中的值保存到Chrome存储中,所以现在您只需要从此处读取值即可。因为content scriptoption在不同的上下文中,所以我们要做的就是找到这两个上下文可以连接的位置,在这种情况下为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.syncchrome.storage.local,您可能已经知道,但以防万一。

  • [chrome.storage.sync,使用您的帐户登录以同步浏览数据的Chrome浏览器之间同步数据,该操作具有读/写limitation

  • chrome.storage.local不会同步数据,基本上它只是将数据存储在安装了扩展程序的浏览器中。此函数有存储大小限制(只能存储最大5,242,880个字节),您可以读取this document以增加它。

© www.soinside.com 2019 - 2024. All rights reserved.