How to catch JavaScript errors in all Iframes (with window.error)?

17,024

Solution 1

This might work.

function myHandler(msg, url, line){
  //do stuff here...
}

//hook in all frames...
function addErrorHandler(win, handler){
  win.onerror = handler;
  for(var i=0;i<win.frames.length;i++){
    addErrorHandler(win.frames[i], handler);
  }
}
//start with this window... and add handler recursively
addErrorHandler(window, myHandler);

Solution 2

I haven't tried this so please don't hang me for it :-) In the master/parent window that holds all of the iframes, you could create your error handing function there. Then use jQuery to grab all of your iFrames in your page and register the .error handler to point to your function registered in the parent window.

PS: Also while were on the topic of javascript error handling, this is pretty cool too: https://damnit.jupiterit.com/

Share:
17,024
Tal
Author by

Tal

Software Engineer at SAP

Updated on July 03, 2022

Comments

  • Tal
    Tal over 1 year

    I know one can add event listener for window.error.

    However when working with Iframes, each iframe has its own window element, and window.error should be created for each and every iframe.

    Is it possible somehow to define error event handler in one location, where all errors will trigger this specific method?