How to catch JavaScript errors in all Iframes (wit

2020-02-05 09:43发布

问题:

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?

回答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);


回答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/