How to simulate target=“_blank” in JavaScript

When a user clicks on a link, I need to update a field in a database and then open the requested link in a new window. The update is no problem, but I don't know how to open a new window without requiring them to click on another hyperlink.

<body onLoad="document.getElementById('redirect').click">
<a href="" id="redirect" target="_blank">Report</a>


<script>'', '_blank');

The second parameter is optional and is the name of the target window.


This might help

var link = document.createElementNS("", "a");
    link.href = ''; = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true

I know this is a done and sorted out deal, but here's what I'm using to solve the problem in my app.

if (!"target")) {
    e.preventDefault();"target", "_blank");;

Basically what is going on here is I run a check for if the link has target=_blank attribute. If it doesn't, it stops the link from triggering, sets it up to open in a new window then programmatically clicks on it.

You can go one step further and skip the stopping of the original click (and make your code a whole lot more compact) by trying this:

if (!"target")) {"target", "_blank");

If you were using jQuery to abstract away the implementation of adding an attribute cross-browser, you should use this instead of"target", "_blank"):

    jQuery("target", "_blank")

You may need to rework it to fit your exact use-case, but here's how I scratched my own itch.

Here's a demo of it in action for you to mess with.

(The link in jsfiddle comes back to this discussion .. no need a new tab :))


I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.


I started using that to bypass the W3C's XHTML strict test.


This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.


    $(".external").click(function(e) {

You can extract the href from the a tag:'redirect').href);

This might help you to open all page links:

     function(i,e){, '_blank');

It will open every <a href="" class="myClass"></a> link items to another tab like you would had clicked each one.

You only need to paste it to browser console. jQuery framework required


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.