Open internal links in same tab or window with JavaScrip

ยท

1 min read

It's better to make external links opened in new tab to decrease bounce rate and improve SEO. And you want to open internal links in same tab or window. If it open in new windows it will increase your bounce rate.

This JavaScript code will make all your internal links open in same tab or window.

// Open internal links in a same tab or a new window

<script>
var links = document.getElementsByTagName("a");
var thisHref = window.location.hostname;
for(var i=0; i<links.length; i++) {
    templink = links[i].href;
    a = getLocation(templink);

    if (a.hostname == thisHref){ // if the link is not same with current page URL
         links[i].removeAttribute("target");
    }
}

    function getLocation(href) {
    var location = document.createElement("a");
    location.href = href;
    if (location.host == "") {
      location.href = location.href;
    }
    return location;
};
</script>
ย