问题描述
我有一些代码,可以让用户选中复选框,并在提交时打开与新选项卡中的复选框相关联的URL.如果两个复选框都被选中,则会打开两个选项卡.它像预期的那样工作,外观如下:
I have some code, which lets user check checkboxes and on submit opens urls associted with checkboxes in new tabs. In case both checkboxes are checked two tabs become opened. It works like expected and looks like:
document.getElementById('cbx').addEventListener(
'submit', function checkForm(event) {
//Prevents default action that would normally happen onsubmit
event.preventDefault();
//Define the form element
var form = document.getElementById("cbx");
if (form.cb1.checked) {
window.open('http://google.com/', '_blank');
}
if (form.cb2.checked) {
window.open('http://yahoo.com/', '_blank');
}
return true;
});
<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
现在我想在我的Chrome扩展程序中包含此功能:
Now i want to include this functionality in my Chrome extension:
- HTML部分位于popup.html中,
- JavaScript部分在popup.js中.
问题是:如果同时选中了两个复选框,则只打开第一个带有url的 cb1
标签.
The problem is: if both checkboxes are checked only one te first cb1
tab with url is opened.
为什么会这样?如果选中了所有复选框,如何打开具有所有相应URL的选项卡?
Why is it so? How can i achieve that if all checkboxes are checked, tabs with all according urls become opened?
推荐答案
打开并聚焦,新标签会自动关闭弹出窗口.
Opening and focusing a new tab will automatically close the popup.
有两种解决方案:
-
打开除第一个以外的所有标签页
Open all tabs except the first one as inactive
const urls = [
form.cb1.checked && 'http://google.com/',
form.cb2.checked && 'http://yahoo.com/',
].filter(Boolean);
urls.reduceRight((_, url, index) => chrome.tabs.create({url, active: !index}), 0);
使用背景脚本:使用网址从弹出窗口发送消息因此后台脚本将通过chrome.tabs.create打开它们.这是更可靠的,因为另一个扩展程序可以激活通过第一种方法打开的非活动选项卡,从而关闭弹出窗口,这可能会(也可能不会)在创建第二个选项卡之前发生.
Use a background script: send a message from the popup with the URLs so the background script will open them via chrome.tabs.create. This is more reliable because another extension could activate an inactive tab opened via the first method, thus closing the popup, which may (or may not) happen before the second tab is created.
这篇关于从popup.html和popup.js打开两个新选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!