plugin development – Best way to add onclick function to all internal links using javascript
As part of a plugin, I am looping all <a>
link tags on a page and adding an onclick
attribute.
But I only want to add the onclick
attribute IF the link URL is on the same site… So I am using the siteurl
option value as part of this detection. (Also, I I realize I could add a click
event listener instead… I’m not sure if there is any advantage to that approach.)
Here is what I have so far (extracted and simplified to make it easier to read):
var siteurl="<?php echo get_option("siteurl"); ?>";
var ignoreclasses = [ 'external' ];
alinks = document.getElementsByTagName('a');
for (var i = 0; i < alinks.length; i++) {
if ( !alinks[i].onclick && !alinks[i].getAttribute('onclick') && (alinks[i].href != '')
&& !alinks[i].getAttribute('target') && (alinks[i].href.indexOf('javascript:') !== 0) ) {
skip = false;
if (ignoreclasses.length) {
for (i in ignoreclasses) {
if (alinks[i].classList.contains(ignoreclasses[i])) {skip = true;}
}
}
if (!skip) {
external = is_link_external(alinks[i]);
if (!external) {alinks[i].setAttribute('onclick', 'return my_function(this);');}
}
}
}
function is_link_external(el) {
/* treat hash or query as internal */
u = el.href; a="#"; b = '?';
if ((u.indexOf(a) === 0) || (u.indexOf(b) === 0)) {return false;}
/* check against site URL */
if ((siteurl != '') && (u.indexOf(siteurl) === 0)) {return false;}
/* check against host/protocol */
if (el.host == window.location.host) {
a = window.location.protocol+'//'+window.location.host;
b = '//'+window.location.host;
if ((u.indexOf(a) === 0) || (u.indexOf(b) === 0)) {return false;}
}
return true;
}
So that is what I have so far and it seems to be working well, my question is, am I missing anything? Are there any weird URLs that fall outside of this scope that I haven’t thought of? Or maybe there are other edge cases or some possibility that could trigger an error somewhere. I just want this code to be as robust as possible.
Leave an answer