Open internal links in same tab or window (JavaScript)

It's desirable to make external links opened in new tab to decrease bounce rate and improve SEO. Also, you might want to open internal links in same tab or window. If the internal links are opened in same tab, it is likely to trigger Google interstitial ads on mobile devices, , which will increase AdSense Revenue.

How to open internal links in same tab or window using JavaScript

Open internal links in same tab or window (JavaScript)

You can use a WordPress plugin such as External Links in New Window / New Tab to open external links in a new tab or a or new window in WordPress.

If you want to make internal links opened in same tab, you can try the following JavaScript code:

// 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>

If you think the above code snippet needs improvement, please let me know via the comments below.

See Also...


Leave a Comment

3s