Open a URL in a new tab (and not a new window) using 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:,'_blank');;

But none of them worked for me, the browser still tried to open a popup window.


Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference.

CSS3 proposed target-new, but the specification was abandoned.

The reverse is not true; by specifying dimensions for the window in the third argument of, you can trigger a new window when the preference is for tabs.

This is a trick,

function openInNewTab(url) {
  var win =, '_blank');

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('');">Something To Click On</div> 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">

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. Cannot Reliably Open Popups in a New Tab in All Browsers

Different browsers implement the behavior of in different ways, especially with regard to a user's browser preferences. You cannot expect the same behavior for 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, as alluded to in Quentin's answer.

As for Firefox (29) users, using, '_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).


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

Internet Explorer (11)

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

<!DOCTYPE html>

    <button onclick="'');">
    <button onclick="'', '_blank');">
      <code>, '_blank')</code>

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 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 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>

    <button onclick="'', 'test', 'width=400, height=400');">

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 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.


Different browsers implement the behavior of differently with regard to users' browser preferences. You cannot expect the same behavior for 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

One liner:

Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();

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

And if you want, based on that you can create some function:

function openInNewTab(href) {
  Object.assign(document.createElement('a'), {
    target: '_blank',

and then you can use it like:


If you use, '_blank'), it will be blocked (popup blocker) on Chrome.

Try this:

//With JQuery

$('#myButton').click(function () {
    var redirectWindow ='', '_blank');

With pure JavaScript,

document.querySelector('#myButton').onclick = function() {
    var redirectWindow ='', '_blank');

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).

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

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:

    url: "url",
    type: "POST",
    success: function() {'url', '_blank');              

But this may open in a new tab, depending on browser settings:

    url: "url",
    type: "POST",
    async: false,
    success: function() {'url', '_blank');              

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

Just omitting [strWindowFeatures] parameters will open a new tab, UNLESS the browser setting overrides (browser setting trumps JavaScript).

New window
var myWin =, strWindowName, [strWindowFeatures]);
New tab
var myWin =, strWindowName);

-- or --

var myWin =;

a.setAttribute('href', location.href);
    e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
    return e

You can use a trick with form:

$(function () {
    $('#btn').click(function () {
        return false;

function openNewTab(link) {
    var frm = $('<form   method="get" action="' + link + '" target="_blank"></form>')

jsFiddle demo

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");

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");
  e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                    false, false, false, false, 0, null);
  return e

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>
    #firing_div {
      margin-top: 15px;
      width: 250px;
      border: 1px solid blue;
      text-align: center;
  <a id="my_link" href=""> Go to Google </a>
  <div id="firing_div"> Click me to trigger custom click </div>
  function fire_custom_click() {
    alert("firing click!");
      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.getElementById("firing_div").onclick = fire_custom_click;

Or you could just create a link element and click it...

var evLink = document.createElement('a');
evLink.href = 'http://' + strUrl; = '_blank';
// Now delete it

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 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:


Here you go! Works a charm for me.

If it is something that you are just trying to load onto the element, try using this. On page load it will add your target property with the correct attribute.

$(your_element_here).prop('target', '_blank');

function openTab(url) {
  const link = document.createElement('a');
  link.href = url; = '_blank';

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.


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:

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

gBrowser.selectedTab = gBrowser.addTab("");

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>


        var url = $(this).attr('data-url');
        var win =, '_blank');  ///similar to above solution

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="'MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

It seems to actually override the browser settings.

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

$('.myBtn').on('click', function(event) {
<a href="#" class="myBtn" target="_blank">Go</a>

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 ("" 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 is SUPPOSED to keep the new page from replacing the existing page
 wnd ="", "_blank"); //get reference to just-opened page
 //if the "general rule" above is true, a new tab should have been opened.
 URL = "";  //ultimate destination
 setTimeout(gotoURL(),200);  //wait 1/5 of a second; give browser time to create tab/window for empty page

 function gotoURL()
 {, "_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

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

    var hostname = window.location.hostname.replace('www.', '');
        var link_host = $(this).attr('hostname').replace('www.', '');
        if (link_host !== hostname) {
            $(this).attr('target', '_blank');

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

    function initOptions(options) {
        options = options || {};
        if (options.wrapping)
            wrapping = options.wrapping;
        else {
            options.serverdomain = options.serverdomain || "";
            options.size = options.size || "800x600";
   = "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"
        if (options.period)
            switch (options.period.toLowerCase()) {
                case "minute":
                    expires = options.duration * 60 * 1e3;
                case "hour":
                    expires = options.duration * 60 * 60 * 1e3;
                case "day":
                    expires = options.duration * 24 * 60 * 60 * 1e3
        posX = typeof options.left != "undefined" ? options.left.toString() : window.screenX;
        posY = typeof != "undefined" ? : 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);
            document.attachEvent("onclick", listenerEvent)

    function removeEvent(listenerEvent) {
        if (document.removeEventListener)
            document.removeEventListener("click", listenerEvent, false);
            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)
                if (isCapped())
                if ( && 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);
          "javascript:window.focus()", "_self", "");
                    popunder = null
                } else
                    popunder =, Math.random().toString(36).substring(7), features);
                if (wrapping) {
                    popunder.document.write("<html><head></head><body>" + unescape(wrapping || "") + "</body></html>");
           = 0
                if (popunder) {
                    now = new Date;
                    next = new Date(now.setTime(now.getTime() + expires));
                    setCookie((+cookie[0] || 0) + 1, next);
    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;
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);

    function moveUnder() {
        try {
            if (browser.firefox)
            else if (browser.webkit)
                browser.msie && setTimeout(function() {
                }, 1e3)
        } catch (e) {}

    function openCloseWindow() {
        var tmp ="about:blank");
        setTimeout(function() {
            try {
                tmp ="about:blank");
            } catch (e) {}
        }, 1)

    function openCloseTab() {
        var ghost = document.createElement("a"),
        clk = document.createEvent("MouseEvents");
        clk.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
        ghost.parentNode.removeChild(ghost);"about:blank", "PopHelper").close()

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="" rel="">new tab</a>

And add some jQuery code:

jQuery(document).ready(function () {
        var w ='','_blank');
        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.

Need Your Help

Running two projects at once in Visual Studio

visual-studio visual-studio-2010 visual-studio-2015

I created a solution in Visual C# 2010 Express that contains two projects: one is the client, the other is the server. I would like to debug both at the same time, but I can only seem to run one of...