Dear Friends, I have a website and on the tutorials web page I have 100+ urls. Few assets are linked to my site and few are 3rd party links. I need a script which excludes my links and all 3rd party links are opened in a new tab even if I do not add target="_blank" or onclick().The Code should not be applied manually on all links, it should be one simple code that can be updated in a JS file. Thanks in advance.
Personally, I don't see how you can separate your 3d party links from your own UNLESS they have a unique ID or class. If they do you can try a jquery option. For instance, if your 3d party links have a class "marketing" (i.e. <a class="marketing" href="https://www.google.com">Visit Google</a>) you can do this number: <script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script> <script> $(document).ready(function () { $("a.marketing").click(function () { window.open($(this).attr("href")); return false; }); }); </script> Code (markup): I am sure there's a way of doing the same thing with pure javascript, but I couldn't find anything working out there.
Of course you can separate them without adding classes. Just check whether it is a full URL, and if it is, check to see if the domain is the current one or an external one. However, with a lot of links it's gonna be a bit taxing if you do it in javascript, so the sane solution is either doing it on the backend or manually by adding a class to the internal urls.
You can put classes and target to out links like that: <a href="http://www.mywebsite.com/link.html">local</a> <a href="http://www.outsidewebsite/link.html">outside</a> <a href="http://www.outsidewebsite/link.html">outside</a> var allLinks = document.getElementsByTagName("a"), linksLength = allLinks.length, myWebsiteDomain = "mywebsite.com"; for (var i = 0; i < linksLength; i++) { if (allLinks[i].href.indexOf("http://") !== -1 && allLinks[i].href.indexOf(myWebsiteDomain) === -1) { allLinks[i].setAttribute("class", "outsideLinks"); allLinks[i].setAttribute("target", "_blank"); } } Code (markup):
The following jQuery code would serve. var hostRegExp = new RegExp(location.host); $(document).on('click', 'a', function(e) { e.preventDefault(); var href = this.href; window.open(href, hostRegExp.test(href) ? '_self' : '_blank'); }); Code (JavaScript):
But this will open all links in new windows. The OP wants only the 3d party links to do that. When I run a test it seems like the code opens all links in a new window. The jsfiddle link should open in the same window, but it doesn't: https://jsfiddle.net/kpppq3a4/2/
The url of the result page of that JSFiddle entry is https://fiddle.jshell.net/kpppq3a4/2/show/ so the entry is unable to yield expected result.
My bad. When I use <a href="/">JSFIDDLE</a> instead of an actual link, it does open it (the jsfiddle's link) in the same window: https://jsfiddle.net/kpppq3a4/6/