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:
<a href="javascript:void(0);" onclick="location.href='https://dirask.com/'"></a>
1. Creating new element with void operator inside href
In this example, we create a new anchor element and prevent it from being opened in a new tab using the void operator.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<a href="javascript:void(0)"
onclick="location.href='https://dirask.com/'">Try to open this link in new tab</a>
</body>
</html>
2. JavaScript code to modify existing element
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.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<a id="link" href="https://dirask.com/">Try to open this link in new tab</a>
<script>
var link = document.querySelector('#link');
var url = link.getAttribute('href');
link.href = 'void(0)';
link.onclick = function() {
location.assign(url);
};
</script>
</body>
</html>