JavaScript global event mechanism

前端 未结 10 2073
无人及你
无人及你 2020-11-22 14:39

I would like to catch every undefined function error thrown. Is there a global error handling facility in JavaScript? The use case is catching function calls from flash that

相关标签:
10条回答
  • 2020-11-22 15:15

    You listen to the onerror event by assigning a function to window.onerror:

     window.onerror = function (msg, url, lineNo, columnNo, error) {
            var string = msg.toLowerCase();
            var substring = "script error";
            if (string.indexOf(substring) > -1){
                alert('Script Error: See Browser Console for Detail');
            } else {
                alert(msg, url, lineNo, columnNo, error);
            }   
          return false; 
      };
    
    0 讨论(0)
  • 2020-11-22 15:16
    // display error messages for a page, but never more than 3 errors
    window.onerror = function(msg, url, line) {
    if (onerror.num++ < onerror.max) {
    alert("ERROR: " + msg + "\n" + url + ":" + line);
    return true;
    }
    }
    onerror.max = 3;
    onerror.num = 0;
    
    0 讨论(0)
  • 2020-11-22 15:19

    Does this help you:

    <script type="text/javascript">
    window.onerror = function() {
        alert("Error caught");
    };
    
    xxx();
    </script>
    

    I'm not sure how it handles Flash errors though...

    Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:

    Mimic Window. onerror in Opera using javascript

    0 讨论(0)
  • 2020-11-22 15:27

    One should preserve the previously associated onerror callback as well

    <script type="text/javascript">
    
    (function() {
        var errorCallback = window.onerror;
        window.onerror = function () {
            // handle error condition
            errorCallback && errorCallback.apply(this, arguments);
        };
    })();
    
    </script>
    
    0 讨论(0)
提交回复
热议问题