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

前端 未结 2 1920
面向向阳花
面向向阳花 2020-12-06 03:39

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

相关标签:
2条回答
  • 2020-12-06 03:57

    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);
    
    0 讨论(0)
  • 2020-12-06 04:01

    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/

    0 讨论(0)
提交回复
热议问题