Languages
[Edit]
EN

JavaScript - prevent page from being open in new tab

0 points
Created by:
maryam
1181

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>

See also

  1. HTML - open link in new tab

  2. JavaScript - open link in new tab

References

  1. void operator - JavaScript | MDN
  2. Object.assign() - JavaScript | MDN
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