javascript - 将用户输入作为选项保存到代码中 - Google Chrome 扩展

标签 javascript google-chrome-extension

我正在编写我的第一个 Chrome 扩展程序。现在我想将用户输入(API key )作为选项保存到代码中,以便代码使用此输入运行。

我有一个文件background.js ,它运行我的 code.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {file: "code.js"})
});

我有文件code.js ,看起来像:

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=<API-KEY>','_blank');win.focus();})()

我有文件 options.html使用表单输入 API key ,例如

<label>
Input API Key
<input type="text" id="wptk">
</label>
<button id="save" onclick="save_options()">Save</button>
<div id="status"></div>
<script src="options.js"></script>

此外我还有option.js使用以下代码:

function save_options() {
  var api = document.getElementById('wptk').value;
    chrome.storage.sync.set({
    savedApi: api,
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 750);
  });
}

document.getElementById('save').addEventListener('click', save_options);

所有这些都已在 manifest.json 中, storage也是。

我现在就在这一点:安装扩展后,我从扩展工具栏打开选项,在输入字段中输入一个字符串,然后按保存后我看到触发Option saved消息。

问题:我如何将保存在选项中的用户输入放入code.js ,之后 &k=而不是占位符<API-KEY> .

示例:如果用户输入123在选项中并保存它,我希望在他的 code.js 中代码更改自

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=<API-KEY>','_blank');win.focus();})()

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=123','_blank');win.focus();})()

最佳答案

直接从后台脚本打开新选项卡:

chrome.browserAction.onClicked.addListener(tab => {
  if (!tab.url) return;
  chrome.storage.sync.get('savedApi', ({savedApi}) => {
    chrome.tabs.create({
      url: `https://my-test-tool.com?url=${encodeURIComponent(tab.url)}&k=${savedApi}`,
      index: tab.index + 1,
      openerTabId: tab.id,
    });
  });
});

要打开一个单独的窗口并控制其大小/位置,您可以使用 chrome.windows.create .

关于javascript - 将用户输入作为选项保存到代码中 - Google Chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730379/

相关文章:

javascript - 如何在构造函数中包装使用 Proxy 构造的对象?

javascript - Chrome 扩展麦克风捕获

javascript - 是否可以在 Google Chrome 扩展中使用(或包含)node.js 框架?

javascript - 禁用 Javascript 时重新加载 ajax 的整页

javascript - 如何组合 jQuery 的函数

javascript - 了解正在更新哪一列

javascript - For...of 循环返回意外的未定义

javascript - 单击 Javascript 时替换网页中字符串的所有实例

html - Unicode 图标 : sometimes looks like a wrong encoding

javascript - 如何将消息从内容脚本发送到面板?