我正在编写我的第一个 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/