36

I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).

What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.

I know that <a href="url" target="_blank"> is out. I also know that <a href="#" onclick="window.open(url);"> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <span onclick="window.open(url);"> and then style the SPAN to look like a link.

One solution I'm leaning towards is <a href="url" rel="external"> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.

Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.

UPDATE: I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.

Kon
  • 27,113
  • 11
  • 60
  • 86
  • I did search for similar questions/answers before, but didn't find anything to answer my question. – Kon Oct 24 '08 at 13:09
  • Why is target="_blank" a no no? – David Arno Oct 24 '08 at 13:10
  • 2
    all bad. You should go for unobtrusive script. What happens with a non js browser? How can they use your site/application? – redsquare Oct 24 '08 at 13:20
  • 3
    "Is going to be phased out of XHTML" -- sure. For the past, what, 6 years? Nothing is "phased out" until browsers stop supporting it, which they won't do until people stop writing sites with it. Which means never. :-) – Rahul Oct 24 '08 at 14:41
  • 2
    @redsquare - all for unobstrusive JS but in today's age who cares about people without JS. If they don't have it, they can't use your site. – JM4 Oct 04 '11 at 23:03
  • @JM4 - ok, things have moved on since 2008! Inline js attributes still suck however. – redsquare Oct 05 '11 at 09:05
  • @redsquare That question is SO 2008 anyway :D but supporting non js users is still a big plus in 2012 I think, so you get a "great comment". – vinczemarton Feb 05 '12 at 08:48
  • @gene : There are cases where users should not be given a choice. Eg. DRM videos, university test where other window will continuously monitor student through camera. Now web is going mainstream where we can simulate real world tasks on web as core business applications, and developers should have that much power. – iankit Jan 14 '14 at 11:03

10 Answers10

38

I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:

$(document).ready(function() {
  $('a[rel*=external]').click(function(){
    window.open($(this).attr('href'));
    return false; 
  });
});

I find this the best method because:

  • it is very clear semantically: you have a link to an external resource
  • it is standards-compliant
  • it degrades gracefully (you have a very simple link with regular href attribute)
  • it still allows user to middle-click the link and open it in new tab if they wish
Damir Zekić
  • 15,630
  • 2
  • 34
  • 35
  • Yes, this seems to be my most recently favorite approach. Just wondering if anyone came up with any other slick way. – Kon Oct 24 '08 at 13:28
  • Having to jump through these hoops is probably why the target attribute reappears in XHTML 2.0. – tvanfosson Oct 24 '08 at 13:37
  • @tvanfosson a small correction: it reappears in XHTML5, not XHTML 2.0. XHTML5 is XML serialization of HTML5, while XHTML 2.0 is improvement on XHTML 1.1. Anyhow, rel="external" improves semantic, while target="_blank" is a behaviour directive (which should be left to JS) – Damir Zekić Oct 24 '08 at 13:45
  • Agreed with porneL, but the basic idea is good - use of rel=external. – Kon Oct 31 '08 at 13:12
  • Here is a great blog post covering this that uses the same method -- it might have been influenced by this. http://www.badlydrawntoy.com/2009/03/03/replacing-target_blank-for-strict-xhtml-using-jquery-redux/ – Evan Carroll May 06 '10 at 16:55
  • 1
    You could easily convert that to a [`.live()`](http://api.jquery.com/live) event to catch events on `` tags that are added after the page loads as well. – gnarf Jul 30 '10 at 03:13
  • 3
    Just a side note use rel*=external instead. Note the asterisk. If you have rel="external nofollow" it won't trigger without the asterisk. The asterisk is a search modfier, that says CONTAINS external. – Phliplip Sep 06 '10 at 07:51
  • That's a nice approach. I've wrapped the window.open with a try .. catch. The catch will be thrown if you are on an inapp browser – funktioneer Apr 05 '16 at 09:05
13

Why is target="_blank" a bad idea?

It's supposed to do exactly what you want.

edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)

Igbanam
  • 5,904
  • 5
  • 44
  • 68
Luk
  • 5,371
  • 4
  • 40
  • 55
  • 1
    It will cause the XHTML validator to show an error, because it has been removed from the standard. Personally, I think that was a bad move. Now people come up with sh*t like "" just to get around it and still be "valid". – Tomalak Oct 24 '08 at 13:15
  • In XHTML 1.0 Strict and XHTML >1.1 "target" is not allowed attribute of "a" tag. – Damir Zekić Oct 24 '08 at 13:15
  • It think the problem is with Tabbed browsers. It is not clear whether this means open a new browser, open a new tab or open a sub window of the existing browser. – Martin Brown Oct 24 '08 at 13:18
  • Yes, standards... so this is totally not the answer. And I'm shocked there are so many people who upvoted this. – Kon Oct 24 '08 at 13:20
  • But I don't want it to be clear whether to open in a new tab or a new window. I want that to be up to the user. – Mark Baker Oct 24 '08 at 13:22
  • Show me a browser that follows the standards :D – Gene Oct 24 '08 at 13:32
  • @fallen888 it depends on which standard you want to implement. I use XHTML 1.0 Transitional. FWIW, it is in HTML 5.0 and it does reappear, as far as I can tell, in XHTML 2.0. – tvanfosson Oct 24 '08 at 13:35
  • @Gene, Does that mean a developer shouldn't follow standards? – Kon Oct 24 '08 at 13:36
  • @Gene Safari (since long time manages to complete ACID 3 with 100%), Opera (development version does 100% on ACID 3), Firefox 3.1 is very close... And while 100% result on ACID 3 does not imply perfect support, it is far fetched to say that those browsers are not standards-compliant – Damir Zekić Oct 24 '08 at 13:40
  • 1
    @Mark: it is up to the user already. I can middle click for a new tab, or open a new window from the context menu. There's no way for you to differentiate between the two. – Adam Lassek Oct 24 '08 at 14:16
  • 9
    I've never cared and I don't see myself caring about standards anytime soon because of crap like this. Oh no, we've decided target is no good, so change everything! Well, my target attributes are staying put, and that's that. – Paolo Bergantino Oct 25 '08 at 07:21
  • 2
    @Paolo, no one said to change everything. But moving forward, I think it's a good idea to stay compliant. – Kon Oct 31 '08 at 13:13
11

Please, don't force opening a link in a new window.

Reasons against it:

  • It infringes the rule of the least astonishment.
  • The back-button don't work and the user not possibly knows why.
  • What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?

The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.

A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.

Mnementh
  • 50,487
  • 48
  • 148
  • 202
  • 1
    This doesnt answer the question. What if there is an actual use case for the link to be opened in a new window. Even I get annoyed when this is done without warning, but we should not rule out the actual use cases just for this annoyance. – iankit Jan 14 '14 at 11:06
5

Here is a plugin I wrote for jQuery

 (function($){  
  $.fn.newWindow = function(options) {       
    var defaults = {
        titleText: 'Link opens in a new window'     
    };

     options = $.extend(defaults, options);

     return this.each(function() {  
       var obj = $(this);

       if (options.titleText) {        
           if (obj.attr('title')) {
                     var newTitle = obj.attr('title') + ' (' 
                                                + options.titleText + ')';
           } else {
                    var newTitle = options.titleText;
           };              
           obj.attr('title', newTitle);            
       };          

       obj.click(function(event) {
          event.preventDefault();  
          var newBlankWindow = window.open(obj.attr('href'), '_blank');
          newBlankWindow.focus();
        });     
       });    
  };  
 })(jQuery); 

Example Usage

$('a[rel=external]').newWindow();

You can also change, or remove the title text, by passing in some options

Example to change title text:

$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );

Example to remove it alltogether

$('a[rel=external]').newWindow( { titleText: '' } );
alex
  • 479,566
  • 201
  • 878
  • 984
2

Perhaps I'm misunderstanding something but why don't you want to use target="_blank"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.

BoboTheCodeMonkey
  • 1,157
  • 1
  • 10
  • 18
  • You're right about the JS being enabled being a requirement. I think though that rel=external is an unobtrusive solution, because it's XHTML-compliant and forces an open in a different window only if JS is enabled. – Kon Oct 24 '08 at 13:23
  • For my in house IT application, certain form pages need to be created as new tabs. In Firefox they kept overwriting each other because I gave them a name, but this _blank page name allowed me to create more than one as needed all in their own tabs. So thanks for the tip. – Tony Peterson Apr 03 '09 at 13:00
2
<a href="http://some.website.com/" onclick="return !window.open( this.href );">link text</a>

Details are described in my answer to another question.

Community
  • 1
  • 1
Fczbkk
  • 1,477
  • 1
  • 11
  • 23
1
<a href="http://www.google.com" onclick="window.open(this.href); return false">

This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.

Mark S. Rasmussen
  • 34,696
  • 4
  • 39
  • 58
  • But surely you wouldn't want to put such an onclick handler on every link on your site that requires it be opened in a new window/tab. – Kon Oct 24 '08 at 14:00
  • Why not, while arguably too verbose it is certainly acceptable and in the spirit of the spec. – Evan Carroll May 06 '10 at 16:54
0

If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...

Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():

In plain html:

<a href="..." target="_blank" onclick="window.open(this.href, 'newWin'); return false;">link</a>

If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...

-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)

roenving
  • 2,560
  • 14
  • 14
  • I deactivate js on "some" websites ;) – Luk Oct 24 '08 at 15:57
  • using name for window in window.open is *very* annoying - it will unexpectedly replace content of another window (it's problematic when same name is used for more than one link on the page) – Kornel Oct 29 '08 at 00:28
  • -- amd most browsers accept '_blank' as window-name to open a new browser-window (not all !-) – roenving Oct 29 '08 at 21:15
  • I haven't seen browser that doesn't accept _blank for window name. If you want to support such browser, you could use random name. – Kornel Nov 01 '08 at 20:06
0

If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.

You can trick me in to opening a new tab/window with window.open() or target="_blank", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.

Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.

Shadow2531
  • 11,980
  • 5
  • 35
  • 48
  • It's not always under developer's control how the page should behave. I can't simply introduce 'helper' messages/comments on a large pharmaceutical firm's website. – Kon Oct 24 '08 at 14:42
  • True. FWIW, I see lots of sites that just use a javascript URI in the href to open a new window. Then, when JS is off, the link just doesn't work. Of course, target="_blank" will work just as good and will work with JS off. It may not validate, but it'll work, which is more important. – Shadow2531 Oct 25 '08 at 02:28
0

I use this...

$(function() {
  $("a:not([href^='"+window.location.hostname+"'])").click(function(){
    window.open(this.href);
    return false;
  }).attr("title", "Opens in a new window");
});
Mac
  • 3,352
  • 1
  • 17
  • 4