Open 3rd party website in new window/page

Nitish Kumar Singh
Nitish Kumar Singh
Clock Image 1 minutes
Posted on
March 14, 2020

Open 3rd party website in new window/page


The strategy is very simple.

  • Get all think link (anchor tag) from the website.
  • Iterate through it and do some tweaks
  • We check if the anchor tag href is from our domain or not ?
    • If it is from our domain then we don’t do anything.
    • If domain is not from our domain then we update the target to _BLANK.
var allLink = document.getElementsByTagName('a');

var ourDomain = window.location.origin;

for(var i = 0 ; i < allLinks.length ; i++){
    var link = allLink[i];
    if(link.href.startsWith(ourDomain)){
        // Don't do anything when the link is from our own domain
    }else{
        // add target to _BLANK, so that 3rd party link will be opened in new tab/windows
        allLink[i].target = "_BLANK";
    }
}
Last updated at Friday, Apr 24, 2020 by Nitish Kumar Singh
comments powered by Disqus

Subscribe to our Newsletter

Tweet this article Tweet this article