问题
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>
Now i want to include this functionality in my Chrome extension:
- the HTML part is in popup.html,
- Javascript part is in the popup.js.
The problem is: if both checkboxes are checked only one te first cb1
tab with url is opened.
Why is it so? How can i achieve that if all checkboxes are checked, tabs with all according urls become opened?
回答1:
Opening and focusing a new tab will automatically close the popup.
There are two solutions:
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);
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.
来源:https://stackoverflow.com/questions/60896867/open-two-new-tabs-from-popup-html-and-popup-js