Search code examples
javascripteventsdynamiconerror

window.onerror: url property empty when error in dynamically added script (via script tag)


What I want to be able to do is to know if an error in a dynamically added script occured. That should be accomplished by inspecting the url property of the onerror event parameter.

However, when I add the event listener at the begin of the script, that is before the script tag is dynamically added, the url property is empty if an error inside the dynmically added script occurs.

So I tried to rebind the event after the script tag has been added like

document.head.appendChild(scriptElement);
document.getElementById(scriptTagId).addEventListener('onerror',someErrorFunction);

as well as

scriptElement.setAttribute('onerror','someErrorFunction(event);');
document.head.appendChild(scriptElement);

and also like

document.head.appendChild(scriptElement);
window.addEventListener('onerror',someErrorFunction);

but to no avail. Actually, the error is only even getting caught using the first approach, that is binding the onerror event at the beginning of the script.


Solution

  • I think you are having an issue as you are getting the script element by id. You can use a simple script loader to achieve the end result. The main difference is that it is binding to the onerror and onload properties of the script element rather than using event listenrs

    edit

    I'm not having any problems with this script using window.onerror and binding to onafterscriptexecute instead of onload, and using document.currentScript to get the script tag that threw the error.

    window.onerror = function(message, source, lineno, colno, error){
      console.log('window.error', {
        message,
        source,
        lineno,
        colno,
        error,
        src: document.currentScript.src
      })
    }
    
    function loadScript(src, callback) {
      console.log('loading: ' + src)
      const script = document.createElement('script')
      script.onerror = function() {
        console.log('error loading script: ' + src)
      }
      script.onafterscriptexecute = callback
      script.src = src
      document.head.appendChild(script)
    }
    
    loadScript('http://codepen.io/synthet1c/pen/BLwWOb.js', function(){
      console.log('this aint gonna happen')
    })
    
    loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', function(){
      console.log('success loaded jQuery')
    })