1

I know that this is a similar question to many others, but the problem is that no solution helps.

I am trying to open a link in a new tab after the click on the button. The problem is that I always get the popup instead of new tab. Here's what I've tried so far:

var a = document.createElement("a");
a.target = "_blank";
a.href = url;
a.click();

Simple window.open doesn't work either:

window.open(url, '_blank');

Also I tried every solution from:

Open a URL in a new tab (and not a new window) using JavaScript

Any more ideas?

The50
  • 1,096
  • 2
  • 23
  • 47

1 Answers1

0

You can force the target="_blank" onto an <a> by doing this:

$('.link-tag').click(function() {
    $(this).attr('target', '_blank');
});

This could work in some browsers, but as a commenter said, if the user's preference is set to open in X, then it will not be able to force it to open in Y.

knocked loose
  • 3,142
  • 2
  • 25
  • 46
  • Just wanted to make sure, I guess the only way is to not run it from JS itself, but parse some HTML and make a href element with _blank in it? – The50 Dec 19 '17 at 17:59
  • @The50 You can do the `_blank` either way, but if a user's preference is to open it in a certain way, you can't force the behavior. Their preferences will override your script or markup. – knocked loose Dec 19 '17 at 18:00
  • how is that any different than above? – epascarello Dec 19 '17 at 18:02