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

↘锁芯ラ 提交于 2019-12-17 19:24:00

问题


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/



来源:https://stackoverflow.com/questions/1353664/how-to-catch-javascript-errors-in-all-iframes-with-window-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!