Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 780
Tal Avatar asked Aug 30 '09 11:08

Tal


2 Answers

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);
like image 65
scunliffe Avatar answered Sep 22 '22 10:09

scunliffe


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/

like image 27
7wp Avatar answered Sep 18 '22 10:09

7wp