EN
JavaScript - open link in new tab
8 points
In this short article, we would like to show how in JavaScript open some links in a new tab.
Quick solution:
xxxxxxxxxx
1
window.open('https://some-domain.com/path', '_blank', 'noopener,noreferrer');
or:
xxxxxxxxxx
1
var site = window.open('https://dirask.com', '_blank');
2
3
if (site) {
4
site.opener = null; // prevents against JavaScript code level access from opened page to opening page
5
} else {
6
console.error('It looks like your web browser blocked pop-up windows.');
7
}
Notes:
- opening pages from outside the domain can lead to attacks when we use
_blank
parameter,- many browsers blocks popupping windows this way - sometimes it is better to consider simple link in html code with
target="_blank"
attribute,- to avoid browser blocking effect it is good to run above action inside mouse click event function - check last example.
Read the next sections for more details.
In this approach, it is necessary to create a new link element and simulate clicking on it.
xxxxxxxxxx
1
var a = document.createElement('a');
2
3
a.setAttribute('href', 'https://dirask.com');
4
a.setAttribute('target', '_blank');
5
a.setAttribute('rel', 'noopener noreferrer'); // prevents against JavaScript code level access from opened page to opening page
6
7
a.click();
Note (in 2021): when we use
target="_blank"
attribute in links, in major modern web browsers, it is automatically usedrel="noopener"
attribute behaving to prevent vulnerabilities - check notification here.
Warning: for security reasons, it is important to use rel="noopener" attribute, even if some tools warns us about unnecessary attribute.
In this section, the open in new window action is run during onclick
event to prevent blocking operation.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<a href="https://dirask.com" onclick="event.preventDefault(); var site = window.open(this.href, '_blank'); site.opener = null;">
5
Click me and open new tab
6
</a>
7
</body>
8
</html>