EN
JavaScript - prevent pages from being open in new tab
3
points
In this article, we would like to show you how to prevent pages from being open in a new tab using JavaScript.
Practical example
In this example, we have three anchor elements (links). To prevent them from being opened in a new tab we set their href to void operator.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<a href="https://dirask.com/posts">Try to open this link in new tab</a>
<br />
<a href="https://dirask.com/snippets">Try to open this link in new tab</a>
<br />
<a href="https://dirask.com/questions">Try to open this link in new tab</a>
<script>
function convertLink(link) {
var url = link.href;
link.addEventListener('click', function(e) {
location.assign(url);
});
link.href = 'javascript:void(0)';
}
var links = document.querySelectorAll('a[href]');
for (var i = 0; i < links.length; ++i) {
convertLink(links[i]);
}
</script>
</body>
</html>