How to detect on-page 404 errors using JavaScript?

前端 未结 4 1841
借酒劲吻你
借酒劲吻你 2020-12-05 00:30

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the

4条回答
  •  被撕碎了的回忆
    2020-12-05 01:05

    @alexander-omara gave the solution.

    You can even add it in many files but the window handler can/should be added once.

    I use the singleton pattern to achieve this:

    some_global_object = {
      error: (function(){
         var activate = false;
         return function(enable){
            if(!activate){
               activate = true;
               window.addEventListener('error', function(e){
                  // maybe extra code here...
                  // if(e.target.custom_property)
                  // ...
               }, true);
            }
            return activate;
         };
      }());
    

    Now, from any context call it as many times you want as the handler is attached only once:

    some_global_object.error();
    

提交回复
热议问题