ChatGPT解决这个技术问题 Extra ChatGPT

Open a URL in a new tab (and not a new window)

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 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.
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.
How can I configure Chrome to display it in a new tab, as opposed to a popup?
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, that's the default browser behavior for any link. (For Chrome and Firefox at least.) Has nothing to do with Gmail.

C
Community

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/


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.
@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.
var win = window.open(url, '_blank'); the '_blank' isn't necessary, for 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 <a> or <form> element. The name should not contain any whitespace characters. Note that strWindowName does not specify the title of the new window.
@hydRAnger same window.open() link on MDN: To open a new window on every call of window.open(), use the special value _blank for windowName.
If anything needs a change in browser settings, avoid it!
Q
Quentin

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.


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).
@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.
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.
@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.
@Bondye — The question is asking about new tabs instead of new windows. The fact you get new windows is rather the point.
P
Peter Mortensen

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.


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.
@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.
@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.
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.
does one not need an e.preventDefault() ?
a
aljgom

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


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.
@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.
You can simplify your code as follows: $('<a />',{'href': url, 'target', '_blank'}).get(0).click();
@shaedrich inspired by your snipped I added non-jquery one-liner: Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
Using target="_blank" without rel="noreferrer" and rel="noopener" makes the website vulnerable to window.opener API exploitation attacks (vulnerability description), although note that, in newer browser versions setting target="_blank" implicitly provides the same protection as setting rel="noopener". developer.mozilla.org/en-US/docs/Web/HTML/Element/A
a
aljgom

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:

https://i.stack.imgur.com/IYWRUm.png

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.


You didnt answer the question, you just proved that window.open is inconsistent.
Please provide a solution, this "answer" begs for a solution
M
Mohammed Safeer

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

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

I use the following and it works very well!

window.open(url, '_blank').focus();

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

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

C
Community

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


P
Peter Mortensen

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');              
    }
});

This is getting blocked as a popup in Firefox 28, Chrome 34b, and Safari 7.0.2, all stock settings. :(
"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 <script>open('http://google.com')</script> 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.
a
attacomsian

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();
        });
});

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 — 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.
a
aljgom

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

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

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.
I think this is the cleanest solution
s
spirinvladimir
(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')))

C
Community

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>

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 theandystratton.com/2012/…
@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.
P
Peter Mortensen

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


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

JQuery

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

JS

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

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.
L
Luke Alderton

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.


P
Predrag Davidovic

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.


a
aljgom

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.


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

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

https://i.stack.imgur.com/RCgV9.gif


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.
This will not work in case ad blocker is installed. Current tab will be closed by ad blocker.
P
Peter Mortensen

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/


P
Peter Mortensen

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.


K
Kamil Kiełczewski

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)


"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.
Both the approaches you suggest have been mentioned (and criticized) many times in the previous 56 undeleted answers on this question.
c
c z

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.


S
Smile4ever

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

gBrowser.selectedTab = gBrowser.addTab("http://example.com");

C
CG_DEV

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();
   });

C
Carlos Salazar

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>

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

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
 }

2
2 revs, 2 users 69%

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');
        }
    });
});

This response is not suitable for this question.BUT, this is very useful think! Thank you for your idea!