View RSS Feed

molendijk

Force a page to open in a new tab

Rating: 9 votes, 4.56 average.
There's an increasing number of sites that refuse to be opened in a new window. For instance, the following doesn't work (anymore):
Code:
<a href="javascript: void(0)" onclick="window.open('http://google.com'">open Google in new (traditional) window</a>
In those cases, you can use the following to open the sites in a new tab:
Code:
<a href="javascript: void(0)" onclick="window.open('','_new').location.href='http://google.com'">open Google in new tab</a>
===
Arie.

Submit "Force a page to open in a new tab" to del.icio.us Submit "Force a page to open in a new tab" to StumbleUpon Submit "Force a page to open in a new tab" to Google Submit "Force a page to open in a new tab" to Digg

Tags: None Add / Edit Tags
Categories
Post a JavaScript

Comments

  1. jscheuer1's Avatar
    I think it's invalid in some DOCTYPES, but works just fine in all of them:
    Code:
    <a href="http://www.google.com/" target="_new">New Google</a>
    BTW, even though you're using javascript: void(0) for the href, you should still return false:

    Code:
    <a href="javascript: void(0)" onclick="window.open('','_new').location.href='http://google.com'; return false;">open Google in new tab</a>
    to prevent partial unloading of the page in some browsers. Some (and not just IE) will stop processing javascript or parts of some javascript. Some will stop processing animated gif. There could be other problems. By having a link that doesn't leave the page but that doesn't return false, the browser is allowed to begin the unload process.

    Personally I prefer letting people know (see it in the status bar for browsers that do that) the link by putting it in the href:

    Code:
    <a href="http://www.google.com/" onclick="window.open('','_new').location.href=this.href; return false;">New Google</a>
    which allows you to use this.href in the onclick event, which has implications for making this a portable/assignable function/event.

    You could alternatively use another tag:

    Code:
    <span title="http://www.google.com/" onclick="window.open('','_new').location.href=this.title;">New Google</span>
    This completely eliminates any concern about the page partially unloading. The tag may be styled to look and act like a link. (cursor:pointer;text-decoration:underline; etc.)

    This also appears to work, at least in Firefox:

    Code:
    <span title="http://www.google.com/" onclick="window.open(this.title, '_new');">New Google</span>
    which tends to indicate that the a tag itself is part of the original problem you mention.
  2. molendijk's Avatar
    John, very useful, thanks!
    Arie.