How to simulate target=“_blank” in JavaScript ?

The HTML target attribute defines where the linked document will open when the user clicked on the link. If target=”_blank” is set with anchor element, then the linked document will open in a new tab otherwise document is open in the same tab. There are two methods to execute this task. One is the normal older and lengthy way, where target=”_blank” attribute is written inside the HTML tag. Another convenient way is to execute through javascript code.

Approach: At first we will create an event on every click function then we set the condition if there is an anchor tag and the target attribute is not mentioned, target attribute as “_blank”.

Syntax:

 document.addEventListener("click", function(e) {
    if (e.target.tagName == "A" &&
            !e.target.hasAttribute("target"))
    {
        e.target.setAttribute("target", "_blank");
    }
}); 

Below example illustrate the target=”_blank” in JavaScript:
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Simulate target=“_blank” in JavaScript
    </title>
      
    <script>
        document.addEventListener("click", function(e) {
            if (e.target.tagName == "A" &&
                    !e.target.hasAttribute("target"))
            {
                e.target.setAttribute("target", "_blank");
            }
        });
    </script>
</head>
  
<body style="text-align:center">
      
    <a href="https://www.geeksforgeeks.org/">
        GeeksforGeeks<br>
        A computer science portal for geeks
    </a>
</body>
  
</html>

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.