2605

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.

ashleedawg
  • 18,752
  • 7
  • 68
  • 96
Mark
  • 36,479
  • 11
  • 40
  • 47
  • 93
    This is usually a matter of preference. Some people like windows (and fiercely protect this behavior), some tabs (and fiercely protect this behavior). So you would be defeating a behavior that is generally considered to be a matter of taste, not design. – Jared Farrish Feb 05 '11 at 15:57
  • 48
    Javascript knows nothing about your browser and tabs vs windows, so it is really up to the browser to decide how to open a new window. – Andrey Feb 05 '11 at 15:58
  • 6
    How can I configure Chrome to display it in a new tab, as opposed to a popup? – Mark Feb 05 '11 at 15:58
  • 1
    Unless, of course, you are developing a Firefox addon, or using XULRunner to develop a client: https://developer.mozilla.org/en/Code_snippets/Tabbed_browser **NOTE:** These techniques only work for clients you have some degree of access to the underlying browser, not the window found within normal HTTP pages. – Jared Farrish Feb 05 '11 at 16:00
  • 1
    Is there a way I can tell the browser to open a new blank tab, and then control its location ? – Mark Feb 05 '11 at 16:03
  • 1
    @Mark F - To answer your question about opening links in tabs, try http://www.tothepc.com/archives/open-links-in-new-tab-google-chrome-shortcut/. – Jared Farrish Feb 05 '11 at 16:08
  • 1
    It's probably both good and bad that almost all of these fall prey to pop-up blockers. It would be nice if I could get a user to click "OK" or something and then pop up the page. – jocull Sep 18 '12 at 20:12
  • 12
    Gmail does this somehow, at least in Chrome. Shift+click on an email row and you open that email in a new window. Ctrl+click and you open it in a new tab. Only problem: digging into gmail's obfuscated code is a PITA – Sergio Jun 03 '13 at 16:26
  • 55
    @Sergio, that's the default browser behavior for any link. (For Chrome and Firefox at least.) Has nothing to do with Gmail. – Qtax Aug 01 '13 at 20:28
  • 1
    may be due to browser settings, but for me `window.open(url);` opened it up in new tab of chrome and firefox – Raza Ahmed Aug 30 '13 at 06:18
  • 1
    quora.com does it on clicking a new question link. regardless of where you are, the window opens in a new tab not a new window. Its also using a to do it. – Sangram Singh Nov 12 '13 at 19:16
  • 3
    @SangramSingh, that's not a function of javascript. Quora is simply setting the target attribute of anchor tags to "_blank". If you uncheck, e.g., Firefox's "Open new windows in a new tab instead" option, those links will open new windows rather than tabs. – squidbe Dec 12 '13 at 22:00
  • 1
    @Qtax: If *Shift+Click* and *Ctrl+Click* open new windows differently (according to user preferences), could you trigger a *keypress* event in JS to simulate such a keystroke, and thereby open a new tab (or window) that way? – David R Tribble Aug 26 '16 at 14:51
  • 1
    @DavidRTribble No. You [can't even "real click" on an ``](http://stackoverflow.com/a/28015837/107152) with JS. – Qtax Aug 26 '16 at 15:11
  • 1
    _Chrome_ specific solution (dirty hack, though): `window.open("https://www.google.co.kr/_/chrome/newtab?ie=UTF-8")`. – Константин Ван Jan 23 '18 at 06:48
  • 1
    An alternative: In HTML -> ` ` In Javascript -> `function clickLink(id) { document.getElementById(id).click(); }` – ericgm Feb 06 '18 at 11:30

32 Answers32

2264

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>

http://www.tutsplanet.com/open-url-new-tab-using-javascript/

Community
  • 1
  • 1
Rinto George
  • 32,635
  • 13
  • 50
  • 69
  • 135
    Does not work. Got a message at the right of the address bar: **Popup blocked**. Then I allowed popups. And voilà, it opens in a popup, not a **tab**! Chrome 22.0.1229.94 on OS X Lion. – nalply Oct 21 '12 at 10:28
  • 48
    @b1naryatr0phy That's because you didn't actually test it properly. Change the settings in your browsers. Whether it's opened in a tab or window is determined by your browser's settings. There's nothing you can do by calling window.open (or any Javascript) to choose how to open the new window/tab. – Ian Apr 18 '13 at 13:56
  • Question : I set url without protocol ( for example my.site.com/Controller/Index). As result i get new window (tab) by url such as url of current page (from where i use function OpenInNewTab) plus passed into function url. With protocol window opens by correct link. Why? – user2167382 May 15 '14 at 09:07
  • 3
    var win = window.open(url, '_blank'); the '_blank' isn't necessary, for [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open), the second parameter is strWindowName, for: A string name for the new window. The name can be used as the target of links and forms using the target attribute of an or
    element. The name should not contain any whitespace characters. Note that strWindowName does not specify the title of the new window.
    – hydRAnger Nov 18 '15 at 09:33
  • Is there any way to make this open a new tab without it being a sandboxed iframe? When I use this I get CORS errors because the document.domain value is not changed as it is opened as an iframe. – Ids van der Zee Jun 19 '17 at 11:26
  • Note: You may find that the URL provided to `window.open` simply appends the supplied URL with your current site. Example: If you're on "www.mywebsite.com" and you send "www.anotherwebsite.com" to `window.open`, you might get "www.mywebsite.com/www.anotherwebsite.com". The solution is to reference the root document of the site you'd like to visit, i.e. "http://www.anotherwebsite.com". See: https://stackoverflow.com/questions/23373990/window-open-simply-adds-the-url-to-my-current-url – user Dec 23 '19 at 15:57
  • 3
    @hydRAnger same [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) link on MDN: To open a _new_ window on every call of `window.open()`, use the special value `_blank` for `windowName`. – rdela Jun 07 '20 at 08:32
  • if you want to use it with a tag surrounding anchor tag use `onclick="event.preventDefault();"` in the anchor tag. – wieczorek1990 Jan 21 '21 at 15:08
  • 2
    If anything needs a change in browser settings, avoid it! – mukuljainx May 23 '21 at 14:28
1098

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.

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
  • 3
    How come this is the accepted answer? I've tested the below given answers from duke and arikfr and they work perfectly fine in FF, Chrome and Opera except IE (where it doesn't work) and Safari (where it opens in new window instead of new tab). – CobaltBabyBear Apr 05 '13 at 07:15
  • 49
    @AliHaideri The Javascript has nothing to do with how the new tab/window is opened. It's all determined by your browser's settings. Using `window.open` tells the browser to open something new, then the browser opens up what is chosen in its settings - tab or window. In the browsers you tested with, change the settings to open in a new window instead of a tab and you'll see the others' solutions are wrong. – Ian Apr 18 '13 at 13:53
  • What about if I just want to control it on my own browser? Chrome keeps opening popups for window.open() unless I use Venkat's solution. Holding Ctrl when I click the button also works. – Luke Jun 26 '13 at 22:54
  • @PaulBrown Not if the default browser settings make links open in a new window instead of a new tab. – toon81 Jul 11 '13 at 07:37
  • 289
    Two things that waste other people's time more than telling them something can't be done. (1) Telling them something that can't be done *can* be done. (2) Staying silent and letting them keep looking for a way to do something that can't be done. – Quentin Dec 06 '13 at 08:15
  • 1
    @Luke: If it's a question of how to get this functionality only in your own browser, it's probably a question for the SuperUsers site. – Trevor Apr 07 '14 at 20:36
  • 2
    @Bondye — The question is asking about new **tabs** instead of new windows. The fact you get new **windows** is rather the point. – Quentin Apr 14 '14 at 14:32
418

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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Venkat Kotra
  • 9,815
  • 3
  • 46
  • 49
  • 31
    Would be nice to mark this one as the CORRECT answer. My tests with Chrome v26 (Windows) confirm that if the code is within a button's click handler it opens a new tab and if the code is invoked programmatically, e.g. from the console, then it opens a new window. – CyberFonic Apr 05 '13 at 05:26
  • 2
    @Ian From my testing on browsers with default settings, this answer works in cases where the answers above do not. The accepted answer which says "there is nothing you can do" is only true when the user has changed the default settings. – Garfield Apr 19 '13 at 18:46
  • @Ian For sake of clarity, I mentioned this in answer warning about user settings. "This will work provided user has appropriate settings in the browser." I think majority of users don't change browser settings and this answer works for majority of them. – Venkat Kotra Apr 20 '13 at 07:23
  • 1
    `async: false` doesn't work in Chrome. To open a new window from the callback, you need to first open an empty window before sending the HTTP request and later update it. Here is a [good hack](https://attacomsian.com/blog/javascript-open-url-in-new-tab#asynchronous-http-request). – attacomsian Feb 24 '20 at 20:33
  • does one not need an e.preventDefault() ? – Tristanisginger May 30 '22 at 08:41
302
function openInNewTab(href) {
  Object.assign(document.createElement('a'), {
    target: '_blank',
    href: href,
  }).click();
}

It creates a virtual a element, gives it target="_blank" so it opens in a new tab, gives it proper url href and then clicks it.

and then you can use it like:

openInNewTab("https://google.com"); 

Important note:

openInNewTab (as well as any other solution on this page) must be called during the so-called 'trusted event' callback - eg. during click event (not necessary in callback function directly, but during 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)

Adam Pietrasiak
  • 11,708
  • 7
  • 73
  • 89
  • 9
    Thank you. Your pure-JS has a missing piece -- as Luke Alderton wrote (see below), you need to attach created element to the document body, in your code it is hanging in the void an at least in Firefox 37 it does not do anything. – greenoldman May 24 '15 at 06:55
  • 7
    @mcginniwa Any action like this - if not triggered by user action like mouse click will turn popup-blocker. Imagine that you can just open any url with Javascript without user action - that would be quite dangerous. If you put this code inside event like click function - it will work fine - it's the same with all proposed solutions here. – Adam Pietrasiak Oct 08 '15 at 12:11
  • 4
    You can simplify your code as follows: `$('',{'href': url, 'target', '_blank'}).get(0).click();` – shaedrich Dec 22 '17 at 17:20
  • 13
    @shaedrich inspired by your snipped I added non-jquery one-liner: `Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();` – Adam Pietrasiak Jan 05 '18 at 12:07
  • @shaedrich- How to include a text in the code provided by you which will have the link to the page (specified bu the url)? – Love Putin May 18 '20 at 08:13
  • Auto click worked for me using this solution on Chrome. Thanks. – Avnish alok Aug 07 '20 at 12:43
264

window.open Cannot Reliably Open Popups in a New Tab in All Browsers

Different browsers implement the behavior of window.open in different ways, especially with regard to a user's browser preferences. You cannot expect the same behavior for window.open to be true across all of Internet Explorer, Firefox, and Chrome, because of the different ways in which they handle a user's browser preferences.

For example, Internet Explorer (11) users can choose to open popups in a new window or a new tab, you cannot force Internet Explorer 11 users to open popups in a certain way through window.open, as alluded to in Quentin's answer.

As for Firefox (29) users, using window.open(url, '_blank') depends on their browser's tab preferences, though you can still force them to open popups in a new window by specifying a width and height (see "What About Chrome?" section below).

Demonstration

Go to your browser's settings and configure it to open popups in a new window.

Internet Explorer (11)

Internet Explorer settings dialog 1

Internet Explorer tab settings dialog

Test Page

After setting up Internet Explorer (11) to open popups in a new window as demonstrated above, use the following test page to test window.open:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
  </head>

  <body>
    <button onclick="window.open('https://stackoverflow.com/q/4907843/456814');">
      <code>window.open(url)</code>
    </button>
    <button onclick="window.open('https://stackoverflow.com/q/4907843/456814', '_blank');">
      <code>window.open(url, '_blank')</code>
    </button>
  </body>
</html>

Observe that the popups are opened in a new window, not a new tab.

You can also test those snippets above in Firefox (29) with its tab preference set to new windows, and see the same results.

What About Chrome? It Implements window.open Differently from Internet Explorer (11) and Firefox (29).

I'm not 100% sure, but it looks like Chrome (version 34.0.1847.131 m) does not appear to have any settings that the user can use to choose whether or not to open popups in a new window or a new tab (like Firefox and Internet Explorer have). I checked the Chrome documentation for managing pop-ups, but it didn't mention anything about that sort of thing.

Also, once again, different browsers seem to implement the behavior of window.open differently. In Chrome and Firefox, specifying a width and height will force a popup, even when a user has set Firefox (29) to open new windows in a new tab (as mentioned in the answers to JavaScript open in a new window, not tab):

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
  </head>

  <body>
    <button onclick="window.open('https://stackoverflow.com/q/4907843/456814', 'test', 'width=400, height=400');">
      <code>window.open(url)</code>
    </button>
  </body>
</html>

However, the same code snippet above will always open a new tab in Internet Explorer 11 if users set tabs as their browser preferences, not even specifying a width and height will force a new window popup for them.

So the behavior of window.open in Chrome seems to be to open popups in a new tab when used in an onclick event, to open them in new windows when used from the browser console (as noted by other people), and to open them in new windows when specified with a width and a height.

Summary

Different browsers implement the behavior of window.open differently with regard to users' browser preferences. You cannot expect the same behavior for window.open to be true across all of Internet Explorer, Firefox, and Chrome, because of the different ways in which they handle a user's browser preferences.

Additional Reading

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
93

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;
};
Mohammed Safeer
  • 19,163
  • 8
  • 72
  • 77
  • But in this question, they do not mention about site author. Only want to open a url in new window or new tab. This is browser dependent. We do not need to bother about author. Please check that fiddle. It is working – Mohammed Safeer Aug 13 '15 at 19:01
  • It is found that, it didn't work on js fiddle and plunker, but works when you create an html file. It is because js fiddle, output is displayed on iframe, so new window is blocked because of `the request was made in a sandboxed frame whose 'allow-popups' permission is not set` – Mohammed Safeer Feb 08 '17 at 20:08
74

I use the following and it works very well!

window.open(url, '_blank').focus();
reformed
  • 4,205
  • 10
  • 58
  • 83
Ezequiel García
  • 2,396
  • 17
  • 11
  • 4
    This might open in a new tab or window depending on the browser settings. The question is specifically about opening in a new tab even if the preferences are for a new window. – Quentin Feb 02 '20 at 20:48
  • True, but as we have established. Opening in a tab or window is a user preference. This answer for opening a url in a new window or tab is excellent and simple. – nire Mar 29 '21 at 09:32
72

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();
pseudosavant
  • 6,656
  • 1
  • 35
  • 40
arikfr
  • 3,205
  • 1
  • 24
  • 27
22

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

Community
  • 1
  • 1
Fran Verona
  • 5,340
  • 5
  • 45
  • 84
19

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');              
    }
});
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
karaxuna
  • 26,302
  • 13
  • 78
  • 114
  • 2
    This is getting blocked as a popup in Firefox 28, Chrome 34b, and Safari 7.0.2, all stock settings. :( – Steve Meisner Mar 27 '14 at 13:39
  • 1
    *"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"* - true of Chrome, but not true of all browsers. Save `` to a `.html` file and open it in a fresh install of a recent version of Firefox; you will observe that Firefox happily opens Google in a new tab (perhaps after you tell it to allow popups), not a new window. – Mark Amery May 15 '16 at 21:53
16

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();
        });
});
attacomsian
  • 2,210
  • 21
  • 22
  • Not sure why this is voted down - this worked for me and seems like a clever way to open a tab in a callback. – stevex Oct 23 '20 at 11:38
  • @stevex — It's answering a completely different question to the one that was asked. This answer is about interacting with popup blockers, not opening a new tab when the user's browser preferences are sent to open a new window. – Quentin Oct 25 '20 at 08:36
15

Just omitting [strWindowFeatures] parameters will open a new tab, UNLESS the browser setting overrides (browser setting 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);
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
MannyC
  • 555
  • 5
  • 7
13
function openTab(url) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  link.remove();
}
iamandrewluca
  • 2,755
  • 1
  • 29
  • 37
  • 1
    This might open in a new tab or window depending on the browser settings. The question is specifically about opening in a new tab even if the preferences are for a new window. – Quentin Aug 12 '19 at 08:48
  • 1
    I think this is the cleanest solution – Kar.ma Dec 03 '20 at 09:12
12
(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')))
spirinvladimir
  • 668
  • 7
  • 9
12

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>
Community
  • 1
  • 1
chipairon
  • 1,951
  • 2
  • 19
  • 21
  • 1
    I ended up going to a different solution where I do `w = window.open("placeholder"); $.ajax(...ajax call that returns the url...) success (...w.location = data.url...)` as per http://theandystratton.com/2012/how-to-bypass-google-chromes-javascript-popup-blocker – Paul Tomblin Jan 30 '14 at 14:19
  • 11
    @FahadAbidJanjua It is absolutely *not* correct. **It still depends on browser settings.** There is nothing in HTML or Javascript specifications that declares that a "custom action" must open in a popup rather than a tab. Indeed, **none** of the browsers on my current machine display this behavior. – nmclean Apr 07 '14 at 15:13
12

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
CodeNinja
  • 1,128
  • 2
  • 12
  • 27
  • 4
    If you go by this method, make sure the url doesn't have query params because they'll be skipped by form submit. One solution is to embed hidden input elements inside the form element that have `name` as key & `value` as value for all the parameters inside query params. And then submit the form – Mudassir Ali Feb 16 '16 at 12:49
  • this can be done more simply with an `a` tag instead of a form, and using the jQuery `.click()` method to "submit" it. check [my answer](http://stackoverflow.com/a/36203515/4503698) –  Mar 24 '16 at 21:37
5

JQuery

$('<a />',{'href': url, 'target': '_blank'}).get(0).click();

JS

Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
Bryan
  • 16,283
  • 22
  • 95
  • 121
  • This might open in a new tab or window depending on the browser settings. The question is specifically about opening in a new tab even if the preferences are for a new window. – Quentin Feb 02 '20 at 20:48
4

Do not use target="_blank"

Always use specific name for that window in my case meaningfulName, in this case you save processor resource:

button.addEventListener('click', () => {
    window.open('https://google.com', 'meaningfulName')
})

On this way when you click for example 10 times on button, browser will always re-render 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.

3

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.

Luke Alderton
  • 2,991
  • 1
  • 22
  • 34
3

There is an answer to this question and it is not no.

I found an easy work around:

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! Works a charm for me.

ALZlper
  • 131
  • 1
  • 7
  • 1
    This might open in a new tab or window depending on the browser settings. The question is specifically about opening in a new tab even if the preferences are for a new window. – Quentin Feb 02 '20 at 20:48
2

enter image description here

I researched a lot of information about how to open new tab and stay on the same tab. I have found one small trick to do it. Lets assume you have url which you need to open - newUrl and old url - currentUrl, which you need to stay on after new tab opened. JS code will look something like next:

// init urls
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
// open window with url of current page, you will be automatically moved 
// by browser to a new opened tab. It will look like your page is reloaded
// and you will stay on same page but with new page opened
window.open(currentUrl , '_blank');
// on your current tab will be opened new url
location.href = newUrl;
Vaha
  • 1,539
  • 2
  • 13
  • 24
  • The question is about opening a new tab when the user's preference is to open them in new windows. It isn't asking how to open a URL in a new tab while opening another URL in the existing tab at the same time. – Quentin Feb 02 '20 at 20:47
  • 1
    This will not work in case ad blocker is installed. Current tab will be closed by ad blocker. – Saqib Omer Jan 18 '21 at 11:24
0

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/

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Victor
  • 3,550
  • 2
  • 33
  • 58
0

This might be a hack, but in Firefox if you specify a third parameter, 'fullscreen=yes', it opens a fresh new window.

For example,

<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

It seems to actually override the browser settings.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Kunal
  • 470
  • 2
  • 8
  • 18
0

The window.open(url) will open url in new browser Tab. Belowe JS 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 DOM because we not add it

here is working example (stackoverflow snippets not allow to opening new tab)

Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
  • "The window.open(url) will open url in new browser Tab" — It will follow the user's preference for a new window or a new tab. It won't force a new tab when the preference is for a window. (Which is what the question is about). The same applies to target=_blank. – Quentin Feb 05 '20 at 14:34
  • Both the approaches you suggest have been mentioned (and criticized) many times in the previous 56 undeleted answers on this question. – Quentin Feb 05 '20 at 14:39
-1

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.

c z
  • 6,327
  • 3
  • 35
  • 50
-2

Opening a new tab from within a Firefox (Mozilla) extension goes like this:

gBrowser.selectedTab = gBrowser.addTab("http://example.com");
Smile4ever
  • 3,145
  • 1
  • 24
  • 29
-2

This way is similar to the above solution 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();
   });
CG_DEV
  • 698
  • 7
  • 7
-2

this work for me, just prevent the event, add the url to an <a> tag then trigger the click event on that tag.

Js
$('.myBtn').on('click', function(event) {
        event.preventDefault();
        $(this).attr('href',"http://someurl.com");
        $(this).trigger('click');
});
HTML
<a href="#" class="myBtn" target="_blank">Go</a>
Carlos Salazar
  • 1,580
  • 2
  • 21
  • 42
  • This might open in a new tab or window depending on the browser settings. The question is specifically about opening in a new tab even if the preferences are for a new window. – Quentin Feb 02 '20 at 20:48
-5

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, IE, 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 (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
 }
-9

If you only want to open the external links (links that go to other sites) then this bit of JavaScript/jQuery works well:

$(function(){
    var hostname = window.location.hostname.replace('www.', '');
    $('a').each(function(){
        var link_host = $(this).attr('hostname').replace('www.', '');
        if (link_host !== hostname) {
            $(this).attr('target', '_blank');
        }
    });
});
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Michael
  • 8,406
  • 4
  • 25
  • 36
-9

Somehow a website can do it. (I don't have the time to extract it from this mess, but this is the code)

if (!Array.prototype.indexOf)
    Array.prototype.indexOf = function(searchElement, fromIndex) {
        if (this === undefined || this === null)
            throw new TypeError('"this" is null or not defined');
        var length = this.length >>> 0;
        fromIndex = +fromIndex || 0;
        if (Math.abs(fromIndex) === Infinity)
            fromIndex = 0;
        if (fromIndex < 0) {
            fromIndex += length;
            if (fromIndex < 0)
                fromIndex = 0
        }
        for (; fromIndex < length; fromIndex++)
            if (this[fromIndex] === searchElement)
                return fromIndex;
        return -1
    };
(function Popunder(options) {
    var _parent, popunder, posX, posY, cookieName, cookie, browser, numberOfTimes, expires = -1,
        wrapping, url = "",
        size, frequency, mobilePopupDisabled = options.mobilePopupDisabled;
    if (this instanceof Popunder === false)
        return new Popunder(options);
    try {
        _parent = top != self && typeof top.document.location.toString() === "string" ? top : self
    } catch (e) {
        _parent = self
    }
    cookieName = "adk2_popunder";
    popunder = null;
    browser = function() {
        var n = navigator.userAgent.toLowerCase(),
            b = {
                webkit: /webkit/.test(n),
                mozilla: /mozilla/.test(n) && !/(compatible|webkit)/.test(n),
                chrome: /chrome/.test(n),
                msie: /msie/.test(n) && !/opera/.test(n),
                firefox: /firefox/.test(n),
                safari: /safari/.test(n) && !/chrome/.test(n),
                opera: /opera/.test(n)
            };
        b.version = b.safari ? (n.match(/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n.match(/.+(?:ox|me|ra|ie)[\/:]([\d.]+)/) || [])[1];
        return b
    }();
    initOptions(options);

    function initOptions(options) {
        options = options || {};
        if (options.wrapping)
            wrapping = options.wrapping;
        else {
            options.serverdomain = options.serverdomain || "ads.adk2.com";
            options.size = options.size || "800x600";
            options.ci = "3";
            var arr = [],
                excluded = ["serverdomain", "numOfTimes", "duration", "period"];
            for (var p in options)
                options.hasOwnProperty(p) && options[p].toString() && excluded.indexOf(p) === -1 && arr.push(p + "=" + encodeURIComponent(options[p]));
            url = "http://" + options.serverdomain + "/player.html?rt=popunder&" + arr.join("&")
        }
        if (options.size) {
            size = options.size.split("x");
            options.width = size[0];
            options.height = size[1]
        }
        if (options.frequency) {
            frequency = /([0-9]+)\/([0-9]+)(\w)/.exec(options.frequency);
            options.numOfTimes = +frequency[1];
            options.duration = +frequency[2];
            options.period = ({
                m: "minute",
                h: "hour",
                d: "day"
            })[frequency[3].toLowerCase()]
        }
        if (options.period)
            switch (options.period.toLowerCase()) {
                case "minute":
                    expires = options.duration * 60 * 1e3;
                    break;
                case "hour":
                    expires = options.duration * 60 * 60 * 1e3;
                    break;
                case "day":
                    expires = options.duration * 24 * 60 * 60 * 1e3
            }
        posX = typeof options.left != "undefined" ? options.left.toString() : window.screenX;
        posY = typeof options.top != "undefined" ? options.top.toString() : window.screenY;
        numberOfTimes = options.numOfTimes
    }

    function getCookie(name) {
        try {
            var parts = document.cookie.split(name + "=");
            if (parts.length == 2)
                return unescape(parts.pop().split(";").shift()).split("|")
        } catch (err) {}
    }

    function setCookie(value, expiresDate) {
        expiresDate = cookie[1] || expiresDate.toGMTString();
        document.cookie = cookieName + "=" + escape(value + "|" + expiresDate) + ";expires=" + expiresDate + ";path=/"
    }

    function addEvent(listenerEvent) {
        if (document.addEventListener)
            document.addEventListener("click", listenerEvent, false);
        else
            document.attachEvent("onclick", listenerEvent)
    }

    function removeEvent(listenerEvent) {
        if (document.removeEventListener)
            document.removeEventListener("click", listenerEvent, false);
        else
            document.detachEvent("onclick", listenerEvent)
    }

    function isCapped() {
        cookie = getCookie(cookieName) || [];
        return !!numberOfTimes && +numberOfTimes <= +cookie[0]
    }

    function pop() {
        var features = "type=fullWindow, fullscreen, scrollbars=yes",
            listenerEvent = function() {
                var now, next;
                if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
                    if (mobilePopupDisabled)
                        return;
                if (isCapped())
                    return;
                if (browser.chrome && parseInt(browser.version.split(".")[0], 10) > 30 && adParams.openNewTab) {
                    now = new Date;
                    next = new Date(now.setTime(now.getTime() + expires));
                    setCookie((+cookie[0] || 0) + 1, next);
                    removeEvent(listenerEvent);
                    window.open("javascript:window.focus()", "_self", "");
                    simulateClick(url);
                    popunder = null
                } else
                    popunder = _parent.window.open(url, Math.random().toString(36).substring(7), features);
                if (wrapping) {
                    popunder.document.write("<html><head></head><body>" + unescape(wrapping || "") + "</body></html>");
                    popunder.document.body.style.margin = 0
                }
                if (popunder) {
                    now = new Date;
                    next = new Date(now.setTime(now.getTime() + expires));
                    setCookie((+cookie[0] || 0) + 1, next);
                    moveUnder();
                    removeEvent(listenerEvent)
                }
            };
        addEvent(listenerEvent)
    }
    var simulateClick = function(url) {
        var a = document.createElement("a"),
            u = !url ? "data:text/html,<script>window.close();<\/script>;" : url,
            evt = document.createEvent("MouseEvents");
        a.href = u;
        document.body.appendChild(a);
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
        a.dispatchEvent(evt);
        a.parentNode.removeChild(a)
    };

    function moveUnder() {
        try {
            popunder.blur();
            popunder.opener.window.focus();
            window.self.window.focus();
            window.focus();
            if (browser.firefox)
                openCloseWindow();
            else if (browser.webkit)
                openCloseTab();
            else
                browser.msie && setTimeout(function() {
                    popunder.blur();
                    popunder.opener.window.focus();
                    window.self.window.focus();
                    window.focus()
                }, 1e3)
        } catch (e) {}
    }

    function openCloseWindow() {
        var tmp = popunder.window.open("about:blank");
        tmp.focus();
        tmp.close();
        setTimeout(function() {
            try {
                tmp = popunder.window.open("about:blank");
                tmp.focus();
                tmp.close()
            } catch (e) {}
        }, 1)
    }

    function openCloseTab() {
        var ghost = document.createElement("a"),
            clk;
        document.getElementsByTagName("body")[0].appendChild(ghost);
        clk = document.createEvent("MouseEvents");
        clk.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
        ghost.dispatchEvent(clk);
        ghost.parentNode.removeChild(ghost);
        window.open("about:blank", "PopHelper").close()
    }
    pop()
})(adParams)
Totty.js
  • 14,848
  • 29
  • 100
  • 171
-11

The browser will always open the link in a new tab if the link is on the same domain (on the same website). If the link is on some other domain it will open it in a new tab/window, depending on browser settings.

So, according to this, we can use:

<a class="my-link" href="http://www.mywebsite.com" rel="http://www.otherwebsite.com">new tab</a>

And add some jQuery code:

jQuery(document).ready(function () {
    jQuery(".my-link").on("click",function(){
        var w = window.open('http://www.mywebsite.com','_blank');
        w.focus();
        w.location.href = jQuery(this).attr('rel');
        return false;
    });
});

So, first open new window on same website with _blank target (it will open it in new tab), and then open your desired website inside that new window.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
loshMiS
  • 19