Languages
[Edit]
EN

JavaScript - prevent pages from being open in new tab

3 points
Created by:
sienko
773

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>

 

See also

  1. JavaScript - prevent page from being open in new tab

References

  1. void operator - JavaScript | MDN
  2. Object.assign() - JavaScript | MDN

Alternative titles

  1. JavaScript - prevent links from being open in new tab
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join