6

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?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Tal
  • 1,773
  • 4
  • 18
  • 20

2 Answers2

7

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);
scunliffe
  • 62,582
  • 25
  • 126
  • 161
  • Thanks for that. looks nice, although seems not to be perfect for my app - IFrames and windows are created on the fly without me able to control much of them, so I cannot know in advance all the win objects. I guess there isn't a global error handling way in IE window? Thanks, Tal. – Tal Aug 31 '09 at 06:09
  • ah, in that case... in every frame you create, just add... window.onerror = top.myHandler; – scunliffe Aug 31 '09 at 11:03
  • yes...but I don't know in advance what would be the source of the Iframe. (using form submit to the target IFrame) - the window.onerror should be inside the IFrame code itself.. – Tal Aug 31 '09 at 11:14
  • Hmm, do you have a global JS file that you include in all frames? if so, can your onerror handler go in there? and be hooked in to each window when the script file is loaded? Depending what info you want/need in the error handler, you could check the parent[n], and child[n] frames to determine hierarchy within the error handler. Out of interest... what do you do with the handler? e.g. do you do an AJAX callback to log the error/email system support? or do you just alert the user in a "pretty" way? – scunliffe Aug 31 '09 at 23:50
  • There are several Iframes with a global JS and this is a good idea. Some Iframes are do not have anything in common and created dynamically - any thoughts for that? Regarding the error handler - I'm thinking of doing some AJAX callback for support. but currently this is saved only on client side in some string for later viewing. – Tal Sep 01 '09 at 11:27
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/

7wp
  • 12,505
  • 20
  • 77
  • 103