191

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="http://www.mydomain.com?ReportID=1" id="redirect" target="_blank">Report</a>
</body>
Matt
  • 41,216
  • 30
  • 109
  • 147
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 1
    Hm? `target="_top"` does not open in a new window - `target="_blank"` does. – Tomalak Oct 15 '09 at 17:53
  • If the link is already opening in a new window (due to target="_blank") and the javascript click handler is already updating your database, why would you need to open the new window with Javascript at all? – Joel Mueller Oct 15 '09 at 21:05

10 Answers10

379
<script>
    window.open('http://www.example.com?ReportID=1', '_blank');
</script>

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

joe_young
  • 4,107
  • 2
  • 27
  • 38
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
  • 3
    `window.open` does what `target="_blank"` does - it opens the URL in a new window. – ceejayoz Oct 15 '09 at 18:13
  • 3
    yes. the second argument to window.open() is the "name" you want to give the window, similar to setting a target on a link. https://developer.mozilla.org/En/DOM:window.open – Omer Bokhari Oct 15 '09 at 18:13
  • 2
    Oh, I see. window.open is blocked by Firefox pop-up blocker, but target="_blank" isn't. Should I just ask the client to enable popups from their own website? – Phillip Senn Oct 15 '09 at 18:22
  • 7
    Is there a JavaScript solution that does not get blocked by pop-up blockers like that of Firefox? – ma11hew28 Dec 13 '10 at 01:28
  • 6
    @MattDiPasquale blocking window.open is kinda the point of pop-up blockers! If you make the call in response to a click action it has a better chance of not being blocked. – William Denniss Aug 18 '11 at 15:16
  • remenber to add rel="noopener noreferrer" in order to avoid security leaks – David Soler Apr 03 '20 at 08:53
25

This might help

var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    link.href = 'http://www.google.com';
    link.target = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true
    });
    link.dispatchEvent(event);
Jair Reina
  • 2,606
  • 24
  • 19
18

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 (!e.target.hasAttribute("target")) {
    e.preventDefault();     
    e.target.setAttribute("target", "_blank");
    e.target.click();
    return;
}

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 (!e.target.hasAttribute("target")) {
    e.target.setAttribute("target", "_blank");
}

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

    jQuery(event.target).attr("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 :))

akamaozu
  • 695
  • 1
  • 7
  • 15
  • 1
    I prefer this answer over all because, well, it uses jquery, and it avoids the window.open popup blocker issues. This is perfectly legitimate when dealing with some 3rd party data that contains links which are missing the target. – IncredibleHat Mar 30 '18 at 15:00
9

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

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});
Jindra Helcl
  • 3,457
  • 1
  • 20
  • 26
6

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.

onclick="this.target='_blank';"

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

2

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);
treznik
  • 7,955
  • 13
  • 47
  • 59
2

This is how I do it on my website. Severa buttons call one javascript function, which always opens a new tab for each new web page.

<button type="button" onclick="newTab('http://google.com')">search</button>
<button type="button" onclick="newTab('http://amazon.com')">buy</button>
<button type="button" onclick="newTab('http://gmail.com')">read</button>
<script>
    function newTab(url) {
        window.open(url, '_blank');
    }
</script>
Tommy Paul
  • 21
  • 1
1

This might help you to open all page links:

$(".myClass").each(
     function(i,e){
        window.open(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

radacina
  • 89
  • 2
  • 8
0

When the person is holding shift down and you programmatically want to open a new tab (not a new window) the solution is to wrap a timeout around it.

It depends on your browsers settings but default Chrome behaviour has a problem with "shift down + javascript's window.open()" combination.

someElement.addEventListener('click', (e) => {
    if (e.shiftKey) {
        // Shift down + window.open() requires a "timeout" wrapper
        // Else a "new window" opens instead of a new tab
        setTimeout(() => window.open(url, '_blank'))
    } else {
        // if shift is not down this will open a new tab
        window.open(url, '_blank')
    }
 }
Julesezaar
  • 2,658
  • 1
  • 21
  • 21
-1

changes in js (href='#' target='_blank')

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 03 '22 at 07:38