使用 JavaScript 在新标签页(而不是新窗口)中打开一个 URL

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.

转载于:https://stackoverflow.com/questions/4907843/open-a-url-in-a-new-tab-and-not-a-new-window-using-javascript

csdnceshi77
狐狸.fox An alternative: In HTML -> <button onClick="clickLink('#link')">Open Your Domain On New Tab</button> <a id="link" href="https://yourdomain.com" target="_blank" hidden></a> In Javascript -> function clickLink(id) { document.getElementById(id).click(); }
2 年多之前 回复
csdnceshi78
程序go Chrome specific solution (dirty hack, though): window.open("https://www.google.co.kr/_/chrome/newtab?ie=UTF-8").
2 年多之前 回复
weixin_41568134
MAO-EYE No. You can't even "real click" on an <a> with JS.
接近 4 年之前 回复
csdnceshi79
python小菜 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?
接近 4 年之前 回复
weixin_41568183
零零乙 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.
6 年多之前 回复
weixin_41568110
七度&光 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 <a tag> to do it.
6 年多之前 回复
csdnceshi54
hurriedly% may be due to browser settings, but for me window.open(url); opened it up in new tab of chrome and firefox
接近 7 年之前 回复
weixin_41568134
MAO-EYE that's the default browser behavior for any link. (For Chrome and Firefox at least.) Has nothing to do with Gmail.
大约 7 年之前 回复
weixin_41568208
北城已荒凉 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
大约 7 年之前 回复
csdnceshi74
7*4 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.
接近 8 年之前 回复
csdnceshi72
谁还没个明天 F - To answer your question about opening links in tabs, try tothepc.com/archives/….
9 年多之前 回复
weixin_41568184
叼花硬汉 Is there a way I can tell the browser to open a new blank tab, and then control its location ?
9 年多之前 回复
csdnceshi72
谁还没个明天 Unless, of course, you are developing a Firefox addon, or using XULRunner to develop a client: 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.
9 年多之前 回复
weixin_41568184
叼花硬汉 How can I configure Chrome to display it in a new tab, as opposed to a popup?
9 年多之前 回复
csdnceshi53
Lotus@ 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.
9 年多之前 回复
csdnceshi72
谁还没个明天 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.
9 年多之前 回复

26个回答

This is a trick,

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.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-196/

weixin_41568174
from.. It is working on Chrome Version 66.0.3359.139
大约 2 年之前 回复
csdnceshi79
python小菜 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.
大约 3 年之前 回复
weixin_41568134
MAO-EYE This works. I tested it on Chrome and Firefox. Thanks
4 年多之前 回复
csdnceshi68
local-host 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.
4 年多之前 回复
csdnceshi71
Memor.の It is working fine for me (IE11). Thank you, I upvoted the answer...
接近 5 年之前 回复
csdnceshi53
Lotus@ working fine for me in Chrome 42.0.. although I've configured my browser to open popup windows!
大约 5 年之前 回复
csdnceshi70
笑故挽风 Thank you. It is 2014 year, and its works fine in firefox,chrome and opera!! IE is not the browser ;)
5 年多之前 回复
csdnceshi76
斗士狗 very simple, simply add target="_blank" to that form.
接近 6 年之前 回复
weixin_41568184
叼花硬汉 Can you offer even a single example of a browser in which using the OP's code, the new page opens in a new window, and with yours, it opens in a new tab? So far, you have not offered any example in which this code works, and others have offered plenty in which (they claim) it fails.
大约 6 年之前 回复
csdnceshi65
larry*wei 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?
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ Aurora (Firefox), Chrome, and Opera work fine. IE - brings up new tab fine, but doesn't set focus there: Error: Unable to get property 'focus' of undefined or null reference
6 年多之前 回复
weixin_41568126
乱世@小熊 not working... how you vote for this??
6 年多之前 回复
csdnceshi62
csdnceshi62 popout blocker will go away if you do a synchronous ajax call
6 年多之前 回复
csdnceshi72
谁还没个明天 Chrome 30: works for me and it opens a new tab.
接近 7 年之前 回复
csdnceshi77
狐狸.fox Works great for me! Chrome 29.0.1547.66
接近 7 年之前 回复
csdnceshi64
游.程 Didnt work for me
接近 7 年之前 回复
csdnceshi75
衫裤跑路 Duke - your answer is very close to @venkat-kotra's answer below. Would be nice if you would edit your answer to point out a couple important points in venkat's answer: (1) The window.open statement must be in the click event, (2) if an intermediate ajax query is used, one must use async: false, (3) browser settings may over-ride the desired tab behavior (nothing one can do about this)
大约 7 年之前 回复
csdnceshi73
喵-见缝插针 Opens a new window for me.
大约 7 年之前 回复
csdnceshi69
YaoRaoLov Working on Chrome - Windows :)
大约 7 年之前 回复
csdnceshi61
derek5. 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.
7 年多之前 回复
csdnceshi61
derek5. 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.
7 年多之前 回复
csdnceshi63
elliott.david Agree with you.. Its working for me. Thanks duke my upvote to your answer :)
7 年多之前 回复
weixin_41568208
北城已荒凉 I think the reason so many people are having issues is because they aren't implementing it properly (though I can't see how.) Tested in vanilla: Chrome, IE, FF, SeaMonkey, Safari, and Opera. Works like a charm.
7 年多之前 回复
weixin_41568183
零零乙 not working in chrome. only one link opened in new tab, others opened in different new windows.
7 年多之前 回复
csdnceshi67
bug^君 For Safari (still works in chrome, ff, ie, opera) I found it necessary to do this: var win = window.open(url, '_blank'); win.focus();
7 年多之前 回复
csdnceshi57
perhaps? Isn't working in Safari 6.0.2 on Mac OS X. In my case/configuration a new tab is opened but does not get focused.
7 年多之前 回复
csdnceshi58
Didn"t forge same result in chrome 23. Demo here: d.pr/45CG+
7 年多之前 回复
weixin_41568127
?yb? It works fine for me in Chrome & FF. Make sure any a tags do not have target="_blank" in them
接近 8 年之前 回复
csdnceshi78
程序go 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.
接近 8 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 not working here either, chrome Version 22.0.1229.94 m
接近 8 年之前 回复
csdnceshi54
hurriedly% Come on dude, it works like a charm. Tested in chrome & firefox & that is enough for me.
接近 8 年之前 回复
csdnceshi60
℡Wang Yan It works in all major browsers, where tab style is there
接近 8 年之前 回复
weixin_41568131
10.24 Why does this work? Does it work in all browsers?
接近 8 年之前 回复

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.

csdnceshi63
elliott.david Could you please write this example in plain JS(vanila js), not with jquery? I agree with you @JordanArseno
大约 2 年之前 回复
csdnceshi57
perhaps? Forgive me if I'm missing something obvious ...but, if you're going to take this approach, and have the user click a link... why bother with the JavaScript at all? Just set target='_blank' on the anchor and be done with it... ?
接近 7 年之前 回复
csdnceshi69
YaoRaoLov The async : false bit just saved me alot of time googleing.
大约 7 年之前 回复
csdnceshi53
Lotus@ and others.I just highlighted the warning.
7 年多之前 回复
csdnceshi53
Lotus@ 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.
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 This solution provides open-in-tab as the default behavior (as your fiddle demonstrates). Granted, the user can override that behavior, but most won't. And if they do, then this solution will respect their choice!
7 年多之前 回复
csdnceshi56
lrony* No, it doesn't. There's no guarantee that a tab will open (from Javascript's point of view). Tabs open for me because my browser's default settings are to open in a tab. It works for you and others because your default settings are probably the same. The question said "How to open a URL in a new tab". This, and all other questions with code, answers "How to open a URL based on the browser's default settings". And to me, the OP wants full control. If they want something to happen, the answer should make it happen. These answers might make it happen
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 I don't need total control. I just want a new tab. As you have shown, this solution gives me what I and many others (including the original question) asked for.
7 年多之前 回复
csdnceshi56
lrony* I don't know why you won't accept the fact that you can't control it. All CyberFonic did was explain/prove that it's yet another inconsistency between browsers, and show that insecure window.open calls differ from secure ones..ON CHROME. I just tested the same thing on Firefox and IE and both open in a new tab. Here's an example so you can test your little heart out: jsfiddle.net/gEuMK . Why would you endorse a solution that is inconsistent between browsers and only "works" on one, even though you can't control which happens - a real, secure event or a random/insecure one?
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 If you test carefully with attention to detail, you will find that there is a difference, as CyberFonic pointed out.
7 年多之前 回复
csdnceshi56
lrony* This answer is no different from the others. They all say to use window.open. The second parameter being "_blank" doesn't change anything. Therefore there's no difference here. And the fact they claim "window.open() will not open in new tab if it is not happening on actual click event." is wrong as well. Settings in the browser are the reasoning for anything happening, not Javascript code
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 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.
7 年多之前 回复
csdnceshi56
lrony* No reason to do that, since it's not the correct answer. It doesn't determine how the new tab/browser is opened. You can't control it from Javascript. It's determined by your browser's settings.
7 年多之前 回复
csdnceshi56
lrony* Sorry, it's not. It doesn't determine how the new tab/browser is opened. You can't control it from Javascript. It's determined by your browser's settings.
7 年多之前 回复
csdnceshi52
妄徒之命 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.
7 年多之前 回复

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

weixin_41568127
?yb? You didnt answer the question, you just proved that window.open is inconsistent.
4 年多之前 回复

One liner:

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

or

With jQuery I'm using this one:

var url = "http://google.com";
$("<a>").attr("href", url).attr("target", "_blank")[0].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(url) {
    $("<a>").attr("href", url).attr("target", "_blank")[0].click();
}

and then you can use it like:

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

For a non-jQuery scenario, the function would look like this:

function openInNewTab(url) {
    var a = document.createElement("a");
    a.target = "_blank";
    a.href = url;
    a.click();
}

// And then
openInNewTab("http://google.com");
csdnceshi80
胖鸭 Not working in FF
2 年多之前 回复
csdnceshi58
Didn"t forge That may open in a new tab or a new window as per the user's preferences. The question is asking how to ensure it opens in a new tab and not a new window.
2 年多之前 回复
csdnceshi65
larry*wei inspired by your snipped I added non-jquery one-liner: Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
2 年多之前 回复
weixin_41568127
?yb? You can simplify your code as follows: $('<a />',{'href': url, 'target', '_blank'}).get(0).click();
2 年多之前 回复
weixin_41568131
10.24 This was my first thought. Probably best considering pop-up blockers I would think.
大约 4 年之前 回复
csdnceshi65
larry*wei 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.
接近 5 年之前 回复
csdnceshi73
喵-见缝插针 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.
大约 5 年之前 回复

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');              
    }
});
csdnceshi56
lrony* "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.
大约 4 年之前 回复
csdnceshi80
胖鸭 Is there a workaround to this?
5 年多之前 回复
weixin_41568131
10.24 +1 This was exactly my problem async: false helps but it is dangerous
接近 6 年之前 回复
csdnceshi52
妄徒之命 This is getting blocked as a popup in Firefox 28, Chrome 34b, and Safari 7.0.2, all stock settings. :(
6 年多之前 回复
weixin_41568110
七度&光 Found this useful, so at least some browsers (with default settings) would open the tab without the popup blocker warning.
6 年多之前 回复

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/

csdnceshi78
程序go Triggers popup blocker in Chrome 46.
接近 5 年之前 回复

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

(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')))
weixin_41568131
10.24 In Chrome Version 32.0.1700.102, this code blocked as pop-ups
6 年多之前 回复
csdnceshi62
csdnceshi62 Doesn't open a window or a tab for me.
6 年多之前 回复
csdnceshi64
游.程 This is the only solution that worked for me while trying to open a new tab from a custom JS function. I would prefer to create the element inside the function, but it's ok.
6 年多之前 回复

I use the following and it works very well!!!

window.open(url, '_blank').focus();
csdnceshi76
斗士狗 No. That may open in a new tab or a new window as per the user's preferences. The question is asking how to ensure it opens in a new tab and not a new window.
2 年多之前 回复
csdnceshi61
derek5. -1. This is wrong. The call to .focus() does not affect whether the new page is opened in a window or a tab since it takes place after the .open() call, and window.open(url, '_blank') is literally exactly the code that the question asker included in the question and which he and many other posters here have explained does not work.
大约 4 年之前 回复
weixin_41568134
MAO-EYE causes popup-blocker to appear
4 年多之前 回复

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

Try this:

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});
weixin_41568208
北城已荒凉 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
3 年多之前 回复
csdnceshi53
Lotus@ This isnt working both in FF and chrome.
3 年多之前 回复
csdnceshi71
Memor.の I really think this could be a good solution since it works as expected opening a new tab and also works well even with ad-blockers or pop-up blockers turned on
3 年多之前 回复
csdnceshi77
狐狸.fox Thanks it work fine but browser setting is required to handle popups..
大约 4 年之前 回复
weixin_41568208
北城已荒凉 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
接近 5 年之前 回复
csdnceshi74
7*4 This might open in a new window. This might open in a new tab. Which it is is not under the control of the site author. This code is the same as the code in the question which the OP said didn't work for them.
接近 5 年之前 回复
csdnceshi61
derek5. This is exactly what I expected to see as the accepted answer, is there a reason not to use this option? I tested across Chrome, Safari and IE11 and it works fine in those browsers, but no idea about mobile and LTE(IE10)
大约 5 年之前 回复
共26条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐