Reputation: 2454
I would like to open all links on a given webpage in new tabs at once using JavaScript. Lets take the Stack Overflow question list as an example. Here is what I came up with:
$(".question-hyperlink").each(function(){
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
$(this).click();
})
Unfortunately this does not work at all. I tried using window.open
instead, but still no success. How can I do it?
Upvotes: 2
Views: 290
Reputation: 943142
Unscrupulous spammers would love to be able to make visitors' browsers open a large number of links in new windows at the same time. They'd happily open a dozen pages that the user doesn't want to see and then claim the click-through advertising money.
The user of the browser wouldn't be so happy with this though, so most browsers make it impossible for you to open multiple windows at once.
What you want cannot be done.
Upvotes: 1
Reputation: 8577
The reason your code is not working is that .click()
does not simulate a click by the user, it just fires all the event handlers bound to the click event. So it only runs the JS code you have put in place, and not the browsers reaction to the click.
You can use window.open()
like this:
$(".question-hyperlink").each(function(){
window.open($(this).attr("href"), '_blank');
});
Watch out for pop-up blockers though! If you want to handle them, you can do something like this:
var x = window.open(...);
if(x) {
//The window was opened.
}
else {
//It was blocked.
}
Upvotes: 4