skip to Main Content

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


  1. 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 the onclick property is actually a function before trying to modify it.

    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 (typeof links[i].onclick === 'function') {
                let originalOnclick = links[i].onclick;
                links[i].onclick = function (event) {
                    originalOnclick.call(this, event);
                };
            }
        }
    }
    
    setInterval(changeLinks, 5000);
    
    Login or Signup to reply.
  2. 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:

    document.querySelector('nearestStaticLinkContainerSelector').addEventListener('click', (e) => {
      const tgt = e.target.nearest('a'); // handle child elements
      if (tgt && tgt.getAttribute('href') === '/current') {
        e.preventDefault(); // stop the click
        let currentOnclick = tgt.onclick;
        if (currentOnclick) {
          // do something with the function or use your own function 
        }
        tgt.onclick = null;
      }
    })
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search