How to open url in new tab? [duplicate] - javascript

I'm trying to open a URL in a new tab, as opposed to a popup window.
I've seen related questions where the responses would look something like:
window.open(url,'_blank');
window.open(url);
But none of them worked for me, the browser still tried to open a popup window.

This is a trick,
function openInNewTab(url) {
window.open(url, '_blank').focus();
}
// Or just
window.open(url, '_blank').focus();
In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.
<div onclick="openInNewTab('www.test.com');">Something To Click On</div>
Reference: Open a URL in a new tab using JavaScript

Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)
CSS3 proposed target-new, but the specification was abandoned.
The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.

window.open() will not open in a new tab if it is not happening on the actual click event. In the example given the URL is being opened on the actual click event. This will work provided the user has appropriate settings in the browser.
<a class="link">Link</a>
<script type="text/javascript">
$("a.link").on("click",function(){
window.open('www.yourdomain.com','_blank');
});
</script>
Similarly, if you are trying to do an Ajax call within the click function and want to open a window on success, ensure you are doing the Ajax call with the async : false option set.

This creates a virtual a element, gives it target="_blank", so it opens in a new tab, gives it the proper URL href and then clicks it.
function openInNewTab(href) {
Object.assign(document.createElement('a'), {
target: '_blank',
rel: 'noopener noreferrer',
href: href,
}).click();
}
And then you can use it like:
openInNewTab("https://google.com");
Important note:
This must be called during the so-called 'trusted event' callback—e.g., during the click event (not necessary in a callback function directly, but during a click action). Otherwise opening a new page will be blocked by the browser.
If you call it manually at some random moment (e.g., inside an interval or after server response), it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to poor user experience).

Browsers have different behaviors for how they handle window.open
You cannot expect the behavior to be the same across all browsers. window.open doesn't reliably open pop-ups on a new tab across browsers, and it also depends on the user's preferences.
On Internet Explorer (11), for example, users can choose to open popups in a new window or a new tab, you cannot force Internet Explorer 11 to open popups in a certain way through window.open, as alluded to in Quentin's answer.
As for Firefox (29), the behavior for window.open(url, '_blank') depends on the browser's tab preferences, though you can still force it to open URLs in a popup window by specifying a width and height (see the "Chrome" section below).
Internet Explorer (11)
You can set Internet Explorer to open pop-ups in a new window:
After doing that, try running window.open(url) and window.open(url, '_blank').
Observe that the pages open in a new window, not a new tab.
Firefox (29)
You can also set the tab preference to open new windows, and see the same results.
Chrome
It looks like Chrome (version 34) does not have any settings for choosing to open popups in a new window or a new tab. Although, some ways to do it (editing the registry) are discussed in this question.
In Chrome and Firefox, specifying a width and height will force a popup (as mentioned in the answers here), even when a user has set Firefox to open new windows in a new tab
let url = 'https://stackoverflow.com'
window.open(url, '', 'width=400, height=400')
However, in Internet Explorer 11 the same code will always open a link in a new tab if tabs is chosen in the browser preferences, specifying a width and height will not force a new window popup.
In Chrome, it seems window.open opens a new tab when it is used in an onclick event, and a new window when it is used from the browser console (as noted by other people), and pop-ups open when a width and height are specified.
Additional reading: window.open documentation.

If you use window.open(url, '_blank'), it will be blocked (popup blocker) on Chrome.
Try this:
//With JQuery
$('#myButton').click(function () {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
});
With pure JavaScript,
document.querySelector('#myButton').onclick = function() {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
};

To elaborate Steven Spielberg's answer, I did this in such a case:
$('a').click(function() {
$(this).attr('target', '_blank');
});
This way, just before the browser will follow the link I'm setting the target attribute, so it will make the link open in a new tab or window (depends on user's settings).
One line example in jQuery:
$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.
This can also be accomplished just using native browser DOM APIs as well:
document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();

I use the following and it works very well!
window.open(url, '_blank').focus();

I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.
JavaScript open in a new window, not tab

An interesting fact is that the new tab can not be opened if the action is not invoked by the user (clicking a button or something) or if it is asynchronous, for example, this will not open in new tab:
$.ajax({
url: "url",
type: "POST",
success: function() {
window.open('url', '_blank');
}
});
But this may open in a new tab, depending on browser settings:
$.ajax({
url: "url",
type: "POST",
async: false,
success: function() {
window.open('url', '_blank');
}
});

Whether to open the URL in a new tab or a new window, is actually controlled by the user's browser preferences. There is no way to override it in JavaScript.
window.open() behaves differently depending on how it is being used. If it is called as a direct result of a user action, let us say a button click, it should work fine and open a new tab (or window):
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open a new tab
const tab = window.open('https://attacomsian.com', '_blank');
});
However, if you try to open a new tab from an AJAX request callback, the browser will block it as it was not a direct user action.
To bypass the popup blocker and open a new tab from a callback, here is a little hack:
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open an empty window
const tab = window.open('about:blank');
// make an API call
fetch('/api/validate')
.then(res => res.json())
.then(json => {
// TODO: do something with JSON response
// update the actual URL
tab.location = 'https://attacomsian.com';
tab.focus();
})
.catch(err => {
// close the empty window
tab.close();
});
});

Just omitting the strWindowFeatures parameters will open a new tab, unless the browser setting overrides it (browser settings trumps JavaScript).
New window
var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);
New tab
var myWin = window.open(strUrl, strWindowName);
-- or --
var myWin = window.open(strUrl);

This has nothing to do with browser settings if you are trying to open a new tab from a custom function.
In this page, open a JavaScript console and type:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").click();
And it will try to open a popup regardless of your settings, because the 'click' comes from a custom action.
In order to behave like an actual 'mouse click' on a link, you need to follow spirinvladimir's advice and really create it:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))));
Here is a complete example (do not try it on jsFiddle or similar online editors, as it will not let you redirect to external pages from there):
<!DOCTYPE html>
<html>
<head>
<style>
#firing_div {
margin-top: 15px;
width: 250px;
border: 1px solid blue;
text-align: center;
}
</style>
</head>
<body>
<a id="my_link" href="http://www.google.com"> Go to Google </a>
<div id="firing_div"> Click me to trigger custom click </div>
</body>
<script>
function fire_custom_click() {
alert("firing click!");
document.getElementById("my_link").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
0, 0, 0, 0, 0, /* detail, screenX, screenY, clientX, clientY */
false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
0, null); /* button, relatedTarget */
return e
}(document.createEvent('MouseEvents'))));
}
document.getElementById("firing_div").onclick = fire_custom_click;
</script>
</html>

function openTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}

(function(a) {
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e) {
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))))
}(document.createElement('a')))

You can use a trick with form:
$(function () {
$('#btn').click(function () {
openNewTab("http://stackoverflow.com")
return false;
});
});
function openNewTab(link) {
var frm = $('<form method="get" action="' + link + '" target="_blank"></form>')
$("body").append(frm);
frm.submit().remove();
}
jsFiddle demo

Do not use target="_blank"
Always use a specific name for that window, in my case meaningfulName. In this case you save processor resources:
button.addEventListener('click', () => {
window.open('https://google.com', 'meaningfulName')
})
In this way, when you click, for example, 10 times on a button, the browser will always rerender it in one new tab, instead of opening it in 10 different tabs, which will consume much more resources.
You can read more about this on MDN.

jQuery
$('<a />',{'href': url, 'target': '_blank'}).get(0).click();
JavaScript
Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();

To open a new tab and stay on the same location, you can open the current page in the new tab, and redirect the old tab to the new URL.
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new URL
You will be automatically moved by the browser to a new opened tab. It will look like your page is reloaded and you will stay on same page but on a new window:

Or you could just create a link element and click it...
var evLink = document.createElement('a');
evLink.href = 'http://' + strUrl;
evLink.target = '_blank';
document.body.appendChild(evLink);
evLink.click();
// Now delete it
evLink.parentNode.removeChild(evLink);
This shouldn't be blocked by any popup blockers... Hopefully.

There is an answer to this question and it is not no.
I found an easy workaround:
Step 1: Create an invisible link:
<a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>
Step 2: Click on that link programmatically:
document.getElementById("yourId").click();
Here you go! It works a charm for me.

Here's an example of how we can put it inside an HTML tag
<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>

How about creating an <a> with _blank as target attribute value and the url as href, with style display:hidden with a a children element? Then add to the DOM and then trigger the click event on a children element.
UPDATE
That doesn't work. The browser prevents the default behaviour. It could be triggered programmatically, but it doesn't follow the default behaviour.
Check and see for yourself: http://jsfiddle.net/4S4ET/

This might be a hack, but in Firefox if you specify a third parameter, 'fullscreen=yes', it opens a fresh new window.
For example,
MyPDF
It seems to actually override the browser settings.

The window.open(url) will open the URL in a new browser tab. Below is the JavaScript alternative to it:
let a = document.createElement('a');
a.target = '_blank';
a.href = 'https://support.wwf.org.uk/';
a.click(); // We don't need to remove 'a' from the DOM, because we did not add it
Here is a working example (Stack Overflow snippets do not allow opening a new tab).

There are lots of answer copies suggesting using "_blank" as the target, however I found this didn't work. As Prakash notes, it is up to the browser. However, you can make certain suggestions to the browser, such as to whether the window should have a location bar.
If you suggest enough "tab-like things" you might get a tab, as per Nico's answer to this more specific question for chrome:
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
Disclaimer: This is not a panacea. It is still up to the user and browser. Now at least you've specified one more preference for what you'd like your window to look like.

Opening a new tab from within a Firefox (Mozilla) extension goes like this:
gBrowser.selectedTab = gBrowser.addTab("http://example.com");

This way is similar to the previous solutions, but implemented differently:
.social_icon -> some class with CSS
<div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>
$('.social_icon').click(function(){
var url = $(this).attr('data-url');
var win = window.open(url, '_blank'); ///similar to above solution
win.focus();
});

This works for me. Just prevent the event, add the URL to an <a> tag, and then trigger the click event on that tag.
JavaScript
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href', "http://someurl.com");
$(this).trigger('click');
});
HTML
Go

I'm going to agree somewhat with the person who wrote (paraphrased here): "For a link in an existing web page, the browser will always open the link in a new tab if the new page is part of the same web site as the existing web page." For me, at least, this "general rule" works in Chrome, Firefox, Opera, Internet Explorer, Safari, SeaMonkey, and Konqueror.
Anyway, there is a less complicated way to take advantage of what the other person presented. Assuming we are talking about your own web site ("thissite.com" below), where you want to control what the browser does, then, below, you want "specialpage.htm" to be empty, no HTML at all in it (it saves time sending data from the server!).
var wnd, URL; // Global variables
// Specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); // Get reference to just-opened page
// If the "general rule" above is true, a new tab should have been opened.
URL = "http://www.someothersite.com/desiredpage.htm"; // Ultimate destination
setTimeout(gotoURL(), 200); // Wait 1/5 of a second; give browser time to create tab/window for empty page
function gotoURL()
{
wnd.open(URL, "_self"); // Replace the blank page, in the tab, with the desired page
wnd.focus(); // When browser not set to automatically show newly-opened page, this MAY work
}

Related

How can I open a link in new tab after ajax call? [duplicate]

I'm trying to open a URL in a new tab, as opposed to a popup window.
I've seen related questions where the responses would look something like:
window.open(url,'_blank');
window.open(url);
But none of them worked for me, the browser still tried to open a popup window.
This is a trick,
function openInNewTab(url) {
window.open(url, '_blank').focus();
}
// Or just
window.open(url, '_blank').focus();
In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.
<div onclick="openInNewTab('www.test.com');">Something To Click On</div>
Reference: Open a URL in a new tab using JavaScript
Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)
CSS3 proposed target-new, but the specification was abandoned.
The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.
window.open() will not open in a new tab if it is not happening on the actual click event. In the example given the URL is being opened on the actual click event. This will work provided the user has appropriate settings in the browser.
<a class="link">Link</a>
<script type="text/javascript">
$("a.link").on("click",function(){
window.open('www.yourdomain.com','_blank');
});
</script>
Similarly, if you are trying to do an Ajax call within the click function and want to open a window on success, ensure you are doing the Ajax call with the async : false option set.
This creates a virtual a element, gives it target="_blank", so it opens in a new tab, gives it the proper URL href and then clicks it.
function openInNewTab(href) {
Object.assign(document.createElement('a'), {
target: '_blank',
rel: 'noopener noreferrer',
href: href,
}).click();
}
And then you can use it like:
openInNewTab("https://google.com");
Important note:
This must be called during the so-called 'trusted event' callback—e.g., during the click event (not necessary in a callback function directly, but during a click action). Otherwise opening a new page will be blocked by the browser.
If you call it manually at some random moment (e.g., inside an interval or after server response), it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to poor user experience).
Browsers have different behaviors for how they handle window.open
You cannot expect the behavior to be the same across all browsers. window.open doesn't reliably open pop-ups on a new tab across browsers, and it also depends on the user's preferences.
On Internet Explorer (11), for example, users can choose to open popups in a new window or a new tab, you cannot force Internet Explorer 11 to open popups in a certain way through window.open, as alluded to in Quentin's answer.
As for Firefox (29), the behavior for window.open(url, '_blank') depends on the browser's tab preferences, though you can still force it to open URLs in a popup window by specifying a width and height (see the "Chrome" section below).
Internet Explorer (11)
You can set Internet Explorer to open pop-ups in a new window:
After doing that, try running window.open(url) and window.open(url, '_blank').
Observe that the pages open in a new window, not a new tab.
Firefox (29)
You can also set the tab preference to open new windows, and see the same results.
Chrome
It looks like Chrome (version 34) does not have any settings for choosing to open popups in a new window or a new tab. Although, some ways to do it (editing the registry) are discussed in this question.
In Chrome and Firefox, specifying a width and height will force a popup (as mentioned in the answers here), even when a user has set Firefox to open new windows in a new tab
let url = 'https://stackoverflow.com'
window.open(url, '', 'width=400, height=400')
However, in Internet Explorer 11 the same code will always open a link in a new tab if tabs is chosen in the browser preferences, specifying a width and height will not force a new window popup.
In Chrome, it seems window.open opens a new tab when it is used in an onclick event, and a new window when it is used from the browser console (as noted by other people), and pop-ups open when a width and height are specified.
Additional reading: window.open documentation.
If you use window.open(url, '_blank'), it will be blocked (popup blocker) on Chrome.
Try this:
//With JQuery
$('#myButton').click(function () {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
});
With pure JavaScript,
document.querySelector('#myButton').onclick = function() {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
};
To elaborate Steven Spielberg's answer, I did this in such a case:
$('a').click(function() {
$(this).attr('target', '_blank');
});
This way, just before the browser will follow the link I'm setting the target attribute, so it will make the link open in a new tab or window (depends on user's settings).
One line example in jQuery:
$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.
This can also be accomplished just using native browser DOM APIs as well:
document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();
I use the following and it works very well!
window.open(url, '_blank').focus();
I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.
JavaScript open in a new window, not tab
An interesting fact is that the new tab can not be opened if the action is not invoked by the user (clicking a button or something) or if it is asynchronous, for example, this will not open in new tab:
$.ajax({
url: "url",
type: "POST",
success: function() {
window.open('url', '_blank');
}
});
But this may open in a new tab, depending on browser settings:
$.ajax({
url: "url",
type: "POST",
async: false,
success: function() {
window.open('url', '_blank');
}
});
Whether to open the URL in a new tab or a new window, is actually controlled by the user's browser preferences. There is no way to override it in JavaScript.
window.open() behaves differently depending on how it is being used. If it is called as a direct result of a user action, let us say a button click, it should work fine and open a new tab (or window):
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open a new tab
const tab = window.open('https://attacomsian.com', '_blank');
});
However, if you try to open a new tab from an AJAX request callback, the browser will block it as it was not a direct user action.
To bypass the popup blocker and open a new tab from a callback, here is a little hack:
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open an empty window
const tab = window.open('about:blank');
// make an API call
fetch('/api/validate')
.then(res => res.json())
.then(json => {
// TODO: do something with JSON response
// update the actual URL
tab.location = 'https://attacomsian.com';
tab.focus();
})
.catch(err => {
// close the empty window
tab.close();
});
});
Just omitting the strWindowFeatures parameters will open a new tab, unless the browser setting overrides it (browser settings trumps JavaScript).
New window
var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);
New tab
var myWin = window.open(strUrl, strWindowName);
-- or --
var myWin = window.open(strUrl);
This has nothing to do with browser settings if you are trying to open a new tab from a custom function.
In this page, open a JavaScript console and type:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").click();
And it will try to open a popup regardless of your settings, because the 'click' comes from a custom action.
In order to behave like an actual 'mouse click' on a link, you need to follow spirinvladimir's advice and really create it:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))));
Here is a complete example (do not try it on jsFiddle or similar online editors, as it will not let you redirect to external pages from there):
<!DOCTYPE html>
<html>
<head>
<style>
#firing_div {
margin-top: 15px;
width: 250px;
border: 1px solid blue;
text-align: center;
}
</style>
</head>
<body>
<a id="my_link" href="http://www.google.com"> Go to Google </a>
<div id="firing_div"> Click me to trigger custom click </div>
</body>
<script>
function fire_custom_click() {
alert("firing click!");
document.getElementById("my_link").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
0, 0, 0, 0, 0, /* detail, screenX, screenY, clientX, clientY */
false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
0, null); /* button, relatedTarget */
return e
}(document.createEvent('MouseEvents'))));
}
document.getElementById("firing_div").onclick = fire_custom_click;
</script>
</html>
function openTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}
(function(a) {
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e) {
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))))
}(document.createElement('a')))
You can use a trick with form:
$(function () {
$('#btn').click(function () {
openNewTab("http://stackoverflow.com")
return false;
});
});
function openNewTab(link) {
var frm = $('<form method="get" action="' + link + '" target="_blank"></form>')
$("body").append(frm);
frm.submit().remove();
}
jsFiddle demo
Do not use target="_blank"
Always use a specific name for that window, in my case meaningfulName. In this case you save processor resources:
button.addEventListener('click', () => {
window.open('https://google.com', 'meaningfulName')
})
In this way, when you click, for example, 10 times on a button, the browser will always rerender it in one new tab, instead of opening it in 10 different tabs, which will consume much more resources.
You can read more about this on MDN.
jQuery
$('<a />',{'href': url, 'target': '_blank'}).get(0).click();
JavaScript
Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
To open a new tab and stay on the same location, you can open the current page in the new tab, and redirect the old tab to the new URL.
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new URL
You will be automatically moved by the browser to a new opened tab. It will look like your page is reloaded and you will stay on same page but on a new window:
Or you could just create a link element and click it...
var evLink = document.createElement('a');
evLink.href = 'http://' + strUrl;
evLink.target = '_blank';
document.body.appendChild(evLink);
evLink.click();
// Now delete it
evLink.parentNode.removeChild(evLink);
This shouldn't be blocked by any popup blockers... Hopefully.
There is an answer to this question and it is not no.
I found an easy workaround:
Step 1: Create an invisible link:
<a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>
Step 2: Click on that link programmatically:
document.getElementById("yourId").click();
Here you go! It works a charm for me.
Here's an example of how we can put it inside an HTML tag
<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>
How about creating an <a> with _blank as target attribute value and the url as href, with style display:hidden with a a children element? Then add to the DOM and then trigger the click event on a children element.
UPDATE
That doesn't work. The browser prevents the default behaviour. It could be triggered programmatically, but it doesn't follow the default behaviour.
Check and see for yourself: http://jsfiddle.net/4S4ET/
This might be a hack, but in Firefox if you specify a third parameter, 'fullscreen=yes', it opens a fresh new window.
For example,
MyPDF
It seems to actually override the browser settings.
The window.open(url) will open the URL in a new browser tab. Below is the JavaScript alternative to it:
let a = document.createElement('a');
a.target = '_blank';
a.href = 'https://support.wwf.org.uk/';
a.click(); // We don't need to remove 'a' from the DOM, because we did not add it
Here is a working example (Stack Overflow snippets do not allow opening a new tab).
There are lots of answer copies suggesting using "_blank" as the target, however I found this didn't work. As Prakash notes, it is up to the browser. However, you can make certain suggestions to the browser, such as to whether the window should have a location bar.
If you suggest enough "tab-like things" you might get a tab, as per Nico's answer to this more specific question for chrome:
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
Disclaimer: This is not a panacea. It is still up to the user and browser. Now at least you've specified one more preference for what you'd like your window to look like.
Opening a new tab from within a Firefox (Mozilla) extension goes like this:
gBrowser.selectedTab = gBrowser.addTab("http://example.com");
This way is similar to the previous solutions, but implemented differently:
.social_icon -> some class with CSS
<div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>
$('.social_icon').click(function(){
var url = $(this).attr('data-url');
var win = window.open(url, '_blank'); ///similar to above solution
win.focus();
});
This works for me. Just prevent the event, add the URL to an <a> tag, and then trigger the click event on that tag.
JavaScript
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href', "http://someurl.com");
$(this).trigger('click');
});
HTML
Go
I'm going to agree somewhat with the person who wrote (paraphrased here): "For a link in an existing web page, the browser will always open the link in a new tab if the new page is part of the same web site as the existing web page." For me, at least, this "general rule" works in Chrome, Firefox, Opera, Internet Explorer, Safari, SeaMonkey, and Konqueror.
Anyway, there is a less complicated way to take advantage of what the other person presented. Assuming we are talking about your own web site ("thissite.com" below), where you want to control what the browser does, then, below, you want "specialpage.htm" to be empty, no HTML at all in it (it saves time sending data from the server!).
var wnd, URL; // Global variables
// Specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); // Get reference to just-opened page
// If the "general rule" above is true, a new tab should have been opened.
URL = "http://www.someothersite.com/desiredpage.htm"; // Ultimate destination
setTimeout(gotoURL(), 200); // Wait 1/5 of a second; give browser time to create tab/window for empty page
function gotoURL()
{
wnd.open(URL, "_self"); // Replace the blank page, in the tab, with the desired page
wnd.focus(); // When browser not set to automatically show newly-opened page, this MAY work
}

How to open javascript items array in a new window instead of the same window?

I have a great working code that opens a link in the same window when I click it, it's inside a dropdown menu.
This is in javascript.
problem is that I would like it to open up in a new tab instead of the same window. How can I do this?
here is my code:
items["linkeee"] = {
"label": "mylabel",
"action": function(obj) {
openUrl('http://mypageaa.com/page' + addId);
}
};
update -- also my html looks like this:
mylabel
BUT I don't have direct access to the html without messing stuff up. I gotta do this up there with the javascript
update
how do i combine 'http://mypageaa.com/page' + addId to add , "_blank"
please help thanks
Turn off pop-up blockers for the domain at browser preferences or settings, see chrome Pop-up blocker when to re-check after allowing page. Use window.open()
var w;
items["linkeee"] = {
"label": "mylabel",
"action": function(obj) {
w = window.open("http://mypageaa.com/page", "_blank");
}
};
Alternatively, use <a> element at html with target attribute set to "_blank"
mypageeaa
Using javascript
var a = document.createElement("a");
a.href = "http://mypageaa.com/pagee" + addId; // `encodeURIComponent(addId)`
a.target = "_blank";
document.body.appendChild(a);
a.click();
use window.open instead of your openUrl method, but new window is not guaranteed to open, the browser may block it.
From what I have read in the documentation and several other answers, It appears this behavior depends on user-preference / (user)browser configuration.
From JavaScript's side, there's nothing you can do to reliably open an URL in a new tab
See:
Open a URL in a new tab (and not a new window) using JavaScript
Documentation http://www.w3schools.com/jsref/met_win_open.asp
I suggest using the method
window.open(URL, name, specs, replace);
It defaults to opening a new window. (tab vs window is a user preference)
documentation here.

How do I open Javascript link in new tab [duplicate]

I'm trying to open a URL in a new tab, as opposed to a popup window.
I've seen related questions where the responses would look something like:
window.open(url,'_blank');
window.open(url);
But none of them worked for me, the browser still tried to open a popup window.
This is a trick,
function openInNewTab(url) {
window.open(url, '_blank').focus();
}
// Or just
window.open(url, '_blank').focus();
In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.
<div onclick="openInNewTab('www.test.com');">Something To Click On</div>
Reference: Open a URL in a new tab using JavaScript
Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)
CSS3 proposed target-new, but the specification was abandoned.
The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.
window.open() will not open in a new tab if it is not happening on the actual click event. In the example given the URL is being opened on the actual click event. This will work provided the user has appropriate settings in the browser.
<a class="link">Link</a>
<script type="text/javascript">
$("a.link").on("click",function(){
window.open('www.yourdomain.com','_blank');
});
</script>
Similarly, if you are trying to do an Ajax call within the click function and want to open a window on success, ensure you are doing the Ajax call with the async : false option set.
This creates a virtual a element, gives it target="_blank", so it opens in a new tab, gives it the proper URL href and then clicks it.
function openInNewTab(href) {
Object.assign(document.createElement('a'), {
target: '_blank',
rel: 'noopener noreferrer',
href: href,
}).click();
}
And then you can use it like:
openInNewTab("https://google.com");
Important note:
This must be called during the so-called 'trusted event' callback—e.g., during the click event (not necessary in a callback function directly, but during a click action). Otherwise opening a new page will be blocked by the browser.
If you call it manually at some random moment (e.g., inside an interval or after server response), it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to poor user experience).
Browsers have different behaviors for how they handle window.open
You cannot expect the behavior to be the same across all browsers. window.open doesn't reliably open pop-ups on a new tab across browsers, and it also depends on the user's preferences.
On Internet Explorer (11), for example, users can choose to open popups in a new window or a new tab, you cannot force Internet Explorer 11 to open popups in a certain way through window.open, as alluded to in Quentin's answer.
As for Firefox (29), the behavior for window.open(url, '_blank') depends on the browser's tab preferences, though you can still force it to open URLs in a popup window by specifying a width and height (see the "Chrome" section below).
Internet Explorer (11)
You can set Internet Explorer to open pop-ups in a new window:
After doing that, try running window.open(url) and window.open(url, '_blank').
Observe that the pages open in a new window, not a new tab.
Firefox (29)
You can also set the tab preference to open new windows, and see the same results.
Chrome
It looks like Chrome (version 34) does not have any settings for choosing to open popups in a new window or a new tab. Although, some ways to do it (editing the registry) are discussed in this question.
In Chrome and Firefox, specifying a width and height will force a popup (as mentioned in the answers here), even when a user has set Firefox to open new windows in a new tab
let url = 'https://stackoverflow.com'
window.open(url, '', 'width=400, height=400')
However, in Internet Explorer 11 the same code will always open a link in a new tab if tabs is chosen in the browser preferences, specifying a width and height will not force a new window popup.
In Chrome, it seems window.open opens a new tab when it is used in an onclick event, and a new window when it is used from the browser console (as noted by other people), and pop-ups open when a width and height are specified.
Additional reading: window.open documentation.
If you use window.open(url, '_blank'), it will be blocked (popup blocker) on Chrome.
Try this:
//With JQuery
$('#myButton').click(function () {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
});
With pure JavaScript,
document.querySelector('#myButton').onclick = function() {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
};
To elaborate Steven Spielberg's answer, I did this in such a case:
$('a').click(function() {
$(this).attr('target', '_blank');
});
This way, just before the browser will follow the link I'm setting the target attribute, so it will make the link open in a new tab or window (depends on user's settings).
One line example in jQuery:
$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.
This can also be accomplished just using native browser DOM APIs as well:
document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();
I use the following and it works very well!
window.open(url, '_blank').focus();
I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.
JavaScript open in a new window, not tab
An interesting fact is that the new tab can not be opened if the action is not invoked by the user (clicking a button or something) or if it is asynchronous, for example, this will not open in new tab:
$.ajax({
url: "url",
type: "POST",
success: function() {
window.open('url', '_blank');
}
});
But this may open in a new tab, depending on browser settings:
$.ajax({
url: "url",
type: "POST",
async: false,
success: function() {
window.open('url', '_blank');
}
});
Whether to open the URL in a new tab or a new window, is actually controlled by the user's browser preferences. There is no way to override it in JavaScript.
window.open() behaves differently depending on how it is being used. If it is called as a direct result of a user action, let us say a button click, it should work fine and open a new tab (or window):
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open a new tab
const tab = window.open('https://attacomsian.com', '_blank');
});
However, if you try to open a new tab from an AJAX request callback, the browser will block it as it was not a direct user action.
To bypass the popup blocker and open a new tab from a callback, here is a little hack:
const button = document.querySelector('#openTab');
// add click event listener
button.addEventListener('click', () => {
// open an empty window
const tab = window.open('about:blank');
// make an API call
fetch('/api/validate')
.then(res => res.json())
.then(json => {
// TODO: do something with JSON response
// update the actual URL
tab.location = 'https://attacomsian.com';
tab.focus();
})
.catch(err => {
// close the empty window
tab.close();
});
});
Just omitting the strWindowFeatures parameters will open a new tab, unless the browser setting overrides it (browser settings trumps JavaScript).
New window
var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);
New tab
var myWin = window.open(strUrl, strWindowName);
-- or --
var myWin = window.open(strUrl);
This has nothing to do with browser settings if you are trying to open a new tab from a custom function.
In this page, open a JavaScript console and type:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").click();
And it will try to open a popup regardless of your settings, because the 'click' comes from a custom action.
In order to behave like an actual 'mouse click' on a link, you need to follow spirinvladimir's advice and really create it:
document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))));
Here is a complete example (do not try it on jsFiddle or similar online editors, as it will not let you redirect to external pages from there):
<!DOCTYPE html>
<html>
<head>
<style>
#firing_div {
margin-top: 15px;
width: 250px;
border: 1px solid blue;
text-align: center;
}
</style>
</head>
<body>
<a id="my_link" href="http://www.google.com"> Go to Google </a>
<div id="firing_div"> Click me to trigger custom click </div>
</body>
<script>
function fire_custom_click() {
alert("firing click!");
document.getElementById("my_link").dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
0, 0, 0, 0, 0, /* detail, screenX, screenY, clientX, clientY */
false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
0, null); /* button, relatedTarget */
return e
}(document.createEvent('MouseEvents'))));
}
document.getElementById("firing_div").onclick = fire_custom_click;
</script>
</html>
function openTab(url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
document.body.appendChild(link);
link.click();
link.remove();
}
(function(a) {
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e) {
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e
}(document.createEvent('MouseEvents'))))
}(document.createElement('a')))
You can use a trick with form:
$(function () {
$('#btn').click(function () {
openNewTab("http://stackoverflow.com")
return false;
});
});
function openNewTab(link) {
var frm = $('<form method="get" action="' + link + '" target="_blank"></form>')
$("body").append(frm);
frm.submit().remove();
}
jsFiddle demo
Do not use target="_blank"
Always use a specific name for that window, in my case meaningfulName. In this case you save processor resources:
button.addEventListener('click', () => {
window.open('https://google.com', 'meaningfulName')
})
In this way, when you click, for example, 10 times on a button, the browser will always rerender it in one new tab, instead of opening it in 10 different tabs, which will consume much more resources.
You can read more about this on MDN.
jQuery
$('<a />',{'href': url, 'target': '_blank'}).get(0).click();
JavaScript
Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
To open a new tab and stay on the same location, you can open the current page in the new tab, and redirect the old tab to the new URL.
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new URL
You will be automatically moved by the browser to a new opened tab. It will look like your page is reloaded and you will stay on same page but on a new window:
Or you could just create a link element and click it...
var evLink = document.createElement('a');
evLink.href = 'http://' + strUrl;
evLink.target = '_blank';
document.body.appendChild(evLink);
evLink.click();
// Now delete it
evLink.parentNode.removeChild(evLink);
This shouldn't be blocked by any popup blockers... Hopefully.
There is an answer to this question and it is not no.
I found an easy workaround:
Step 1: Create an invisible link:
<a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>
Step 2: Click on that link programmatically:
document.getElementById("yourId").click();
Here you go! It works a charm for me.
Here's an example of how we can put it inside an HTML tag
<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>
How about creating an <a> with _blank as target attribute value and the url as href, with style display:hidden with a a children element? Then add to the DOM and then trigger the click event on a children element.
UPDATE
That doesn't work. The browser prevents the default behaviour. It could be triggered programmatically, but it doesn't follow the default behaviour.
Check and see for yourself: http://jsfiddle.net/4S4ET/
This might be a hack, but in Firefox if you specify a third parameter, 'fullscreen=yes', it opens a fresh new window.
For example,
MyPDF
It seems to actually override the browser settings.
The window.open(url) will open the URL in a new browser tab. Below is the JavaScript alternative to it:
let a = document.createElement('a');
a.target = '_blank';
a.href = 'https://support.wwf.org.uk/';
a.click(); // We don't need to remove 'a' from the DOM, because we did not add it
Here is a working example (Stack Overflow snippets do not allow opening a new tab).
There are lots of answer copies suggesting using "_blank" as the target, however I found this didn't work. As Prakash notes, it is up to the browser. However, you can make certain suggestions to the browser, such as to whether the window should have a location bar.
If you suggest enough "tab-like things" you might get a tab, as per Nico's answer to this more specific question for chrome:
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
Disclaimer: This is not a panacea. It is still up to the user and browser. Now at least you've specified one more preference for what you'd like your window to look like.
Opening a new tab from within a Firefox (Mozilla) extension goes like this:
gBrowser.selectedTab = gBrowser.addTab("http://example.com");
This way is similar to the previous solutions, but implemented differently:
.social_icon -> some class with CSS
<div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>
$('.social_icon').click(function(){
var url = $(this).attr('data-url');
var win = window.open(url, '_blank'); ///similar to above solution
win.focus();
});
This works for me. Just prevent the event, add the URL to an <a> tag, and then trigger the click event on that tag.
JavaScript
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href', "http://someurl.com");
$(this).trigger('click');
});
HTML
Go
I'm going to agree somewhat with the person who wrote (paraphrased here): "For a link in an existing web page, the browser will always open the link in a new tab if the new page is part of the same web site as the existing web page." For me, at least, this "general rule" works in Chrome, Firefox, Opera, Internet Explorer, Safari, SeaMonkey, and Konqueror.
Anyway, there is a less complicated way to take advantage of what the other person presented. Assuming we are talking about your own web site ("thissite.com" below), where you want to control what the browser does, then, below, you want "specialpage.htm" to be empty, no HTML at all in it (it saves time sending data from the server!).
var wnd, URL; // Global variables
// Specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); // Get reference to just-opened page
// If the "general rule" above is true, a new tab should have been opened.
URL = "http://www.someothersite.com/desiredpage.htm"; // Ultimate destination
setTimeout(gotoURL(), 200); // Wait 1/5 of a second; give browser time to create tab/window for empty page
function gotoURL()
{
wnd.open(URL, "_self"); // Replace the blank page, in the tab, with the desired page
wnd.focus(); // When browser not set to automatically show newly-opened page, this MAY work
}

Force window.open() to create new tab in chrome

I use window.open to populate a new window with varying content. Mostly reports and stored HTML from automated processes.
I have noticed some very inconsistent behavior with Chrome with respect to window.open().
Some of my calls will create a new tab (preferred behavior) and some cause popups.
var w = window.open('','_new');
w.document.write(page_content);
page_content is just regular HTML from AJAX calls. Reports contain some information in the header like title, favicon, and some style sheets.
In IE9 the code does cause a new tab instead of a pop-up, while Chrome flatly refuses to show the content in question in a new tab. Since the content is sensitive business data I cannot post it here. I'll answer questions if I can.
I know some people will say this is behavior left up to the user, but this is an internal business platform. We don't have time to train all the users on how to manage popups, and we just need it to be in a new tab. Heck, even a new window would be preferable to the popup since you cannot dock a popup in Chrome. Not to mention none of the popup blocking code would affect it.
Appreciate any insight.
window.open must be called within a callback which is triggered by a user action (example onclick) for the page to open in a new tab instead of a window.
Example:
$("a.runReport").click(function(evt) {
// open a popup within the click handler
// this should open in a new tab
var popup = window.open("about:blank", "myPopup");
//do some ajax calls
$.get("/run/the/report", function(result) {
// now write to the popup
popup.document.write(result.page_content);
// or change the location
// popup.location = 'someOtherPage.html';
});
});
You can try this:
open a new tab please
<script>
function openWindow(){
var w = window.open("about:blank");
w.document.write("heheh new page opened");
}
</script>
Is very easy, in order to force Chrome to open in a new tab, use the onmouseup event
onmouseup="switchMenu(event);"
I have tried this and it worked fine in chrome. If opening a new tab is on a user action(such as a mouse click) this will work fine without any issues. But if the code is executed in another script block, you may need to enable pop-ups in chrome. Looks like this is to handle all the click-bait sites.
let newTab = window.open('', '_blank');
if (this.viewerTab == null) {
console.log("opening in new tab to work, pop-ups should be enabled.");
return;
}
................
newTab.location.href = viewerUrl;
window.open('page.html', '_newtab');
Specify the '_newtab'. This works in IE and FF, and should work in Chrome. But if the user has things configured to not open in new tab then not much you can do.

How to use target in location.href

I am currently developing a web application where I need to open a popup window to show a report. The problem is that some versions of explorer don't support the window.open javascript function, so when this is the case I catch the error and open the new url with location.href. Here the code:
try {
window.open(url, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
} catch(e) {
location.target = "_blank";
location.href = url;
}
The problem is that the location.target is not working and I would like to know if there is a way to specify the target of the location.href so it can be opened in a new tab.
try this one, which simulates a click on an anchor.
var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();
You can use this on any element where onclick works:
onclick="window.open('some.htm','_blank');"
The problem is that some versions of explorer don't support the window.open javascript function
Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.
Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.
There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".
If you go with the solution by #qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.
// Code by #qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)
Maybe someone could post a comment to his post, because I cannot.
You could try this:
<script type="text/javascript">
function newWindow(url){
window.open(url);
}
</script>
And call the function
If you are using an <a/> to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open() fails, make the default scenario to open a new window via target (and prevent it if window.open() succeeds).
HTML
Link
JS
var spawn = function (e) {
try {
window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
e.preventDefault(); // Or: return false;
} catch(e) {
// Allow the default event handler to take place
}
}
document.getElementById("myLink").onclick = spawn;
Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?
How can I simulate a click to an anchor tag?
This would work in the cases where the window.open did not work
As of 2014, you can trigger the click on a <a/> tag. However, for security reasons, you have to do it in a click event handler, or the browser will tag it as a popup (some other events may allow you to safely trigger the opening).
jsFiddle
<input type="button" value="fake button" />

Categories