I am trying to modify a site to make it open external links in a new tab.
Currently I have a loop which works fine except that it opens ALL links in a new tab which is not desired:
I have tried using filters but can’t seem to get it to work properly.
<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
links[i].setAttribute('target','_blank');
}
});
</script>
Maybe checking if the URL contains a Shopify handle or something along the line?
Thank you in advance!
3
Answers
You can check if the href attributes begins with
http://
,https://
orwww.
since those are the most common external links, all internal usually starts with/
. (you can add an additional check if the href contains the domain name as well since it possible to have internal URL with the full URL)So the code will become something like so:
Maybe something like this?
Note: you don’t need that
document.addEventListener('DOMContentLoaded'...
just putdefer
attribute on your<script>
tagTo get only External links Open in new Tabs, you must use anchor’s property hostname, when its value not matching your “localhostname” string then overwriting anchor’s property target default value "_self"(current browser content) to "_blank"(new tab) value, your script code will be: