I have a simple script that finds every link on page and changes href
and onclick
properties. For some reason I need to run this script every 5 seconds.
function changeLinks() {
let links = document.getElementsByTagName("a");
for (let i = 0; i < links.length; i++) {
links[i].href = links[i].href.replace("/current", "/target");
if (links[i].onclick != null) {
let linkOnClickFunction = links[i].onclick.toString();
linkOnClickFunction = linkOnClickFunction.slice(linkOnClickFunction.indexOf("{") + 1, linkOnClickFunction.lastIndexOf("}"));
linkOnClickFunction = linkOnClickFunction.replace("/current", "/target");
links[i].setAttribute("onclick", linkOnClickFunction);
}
}
}
setInterval(changeLinks, 5000);
The script works fine the first time. However on second execution I get error Unexpected identifier 'Function'
at links[i].onclick
2
Answers
I think, the error occurs because the
onclick
property might contain a function or code that is not handled correctly when you try to modify it. So you should check if theonclick
property is actually a function before trying to modify it.for some reason
perhaps tell us the reason?It looks like an X/Y problem right now since you can replace all onclick with null and/or add a delegated eventlistener: