EN
JavaScript - prevent page from being open in new tab
0 points
In this article, we would like to show you how to prevent a page from being open in a new tab using JavaScript.
Quick solution:
xxxxxxxxxx
1
<a href="javascript:void(0);" onclick="location.href='https://dirask.com/'"></a>
In this example, we create a new anchor element and prevent it from being opened in a new tab using the void operator.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<a href="javascript:void(0)"
5
onclick="location.href='https://dirask.com/'">Try to open this link in new tab</a>
6
</body>
7
</html>
In this example, we modify the existing anchor element's href
to prevent it from being opened in a new tab. Then we add the onclick
event so it can still be opened in the current tab.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<a id="link" href="https://dirask.com/">Try to open this link in new tab</a>
5
<script>
6
7
var link = document.querySelector('#link');
8
var url = link.getAttribute('href');
9
link.href = 'void(0)';
10
link.onclick = function() {
11
location.assign(url);
12
};
13
14
</script>
15
</body>
16
</html>