0

I am trying to create a link by means of the tag "a", click this link and open it in a new tab. My script works but does not open the link in a new tab does it on the same page.

The script is activated by clicking on the "body" element of the web page. Apparently the target = '_blank' is not working.

<script>
function openInNewTab(url) {
    var a = document.createElement("a");
    a.target = '_blank';
    a.href = window.location.href;
    a.click();
    window.location.href = 'https://www.google.com.pe';
    }

$("body").click(function () {
openInNewTab();
});
</script>
Kokox
  • 519
  • 1
  • 9
  • 24
  • Possible duplicate of [How to open a URL in a new Tab using javascript or jquery?](https://stackoverflow.com/questions/19851782/how-to-open-a-url-in-a-new-tab-using-javascript-or-jquery) – Mark Jun 12 '17 at 03:45

4 Answers4

2

change your line

a.target = '_blank';

to

a.setAttribute('target', '_blank');
sifr_dot_in
  • 3,153
  • 2
  • 33
  • 42
0
window.open('https://www.google.com.pe', 'name'); 
  • 'name' is a name of the window. Following names are supported
  • _blank - URL is loaded into a new tab. This is a default.
  • _parent - URL is loaded into the parent frame _self - URL replaces the current page
Karan Singh
  • 876
  • 1
  • 6
  • 12
0
$(document).on('click', 'a', function(e){ 
    e.preventDefault(); 
    var url = $(this).attr('href'); 
    window.open(url, '_blank');
});
Hefm
  • 61
  • 3
  • 13
0

Just use window.open(url,'_blank'); with target blank parameter .

function openInNewTab(url) {
 window.open(url, '_blank');
    }

$("body").click(function () { 

url='https://www.google.com.pe/';
openInNewTab(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
 
 
 <h1>body</h1>
</body>
JYoThI
  • 11,977
  • 1
  • 11
  • 26