Vue monitors the error message on the page, the difference between window.onerror and window.addEventListener('error')

Foreword:

      Monitor the error message on the page

Used in the project: Determine whether there is this version number on the path... The specific content can be based on the actual situation

const asyncVersion = '20210128'
window.addEventListener('error', handleListenerError, true);
    function handleListenerError (eventErr){
      if (eventErr.srcElement.localName.includes('link' || 'script') && !window.location.href.includes('version=' + asyncVersion)) {
        // alert('因版本更新,页面需重新载入,请核对当次操作数据');
        window.location.href= window.location.host + window.location.pathname + '?version=' + VUE_APP_Version
      }
      eventErr.preventDefault()
    }

More:

window.onerror

window.onerror is a global variable, the default value is null. When a js runtime error is triggered, the window will trigger the error event and execute window.onerror(). onerror can accept multiple parameters.

window.onerror = function(message, source, lineno, colno, error) { ... }

函数参数:

*   message:错误信息(字符串)。可用于HTML onerror=""处理程序中的event。
*   source:发生错误的脚本URL(字符串)
*   lineno:发生错误的行号(数字)
*   colno:发生错误的列号(数字)
*   error:Error对象

若该函数返回true,则阻止执行默认事件处理函数,如异常信息不会在console中打印。没有返回值或者返回值为false的时候,异常信息会在console中打印

addEventListener('error')

Listening to js runtime error events will be triggered before window.onerror, which is roughly similar to onerror. However, the event callback function has only one parameter that saves all error information. It cannot prevent the execution of the default event processing function, but it can be captured globally. Resource loading abnormal error

window.addEventListener('error', function(event) { ... })

当资源(如img或script)加载失败,加载资源的元素会触发一个Event接口的error事件,并执行该元素上的onerror()处理函数。这些error事件不会向上冒泡到window,但可以在捕获阶段被捕获
因此如果要全局监听资源加载错误,需要在捕获阶段捕获事件
//图片加载失败使用默认图片,依旧加载失败超过三次使用base64图片
window.addEventListener('error',function(e){
    let target = e.target, // 当前dom节点
        tagName = target.tagName,
        count = Number(target.dataset.count ) || 0, // 以失败的次数,默认为0
        max= 3; // 总失败次数,此时设定为3
    // 当前异常是由图片加载异常引起的
    if( tagName.toUpperCase() === 'IMG' ){
        if(count >= max){
            target.src = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD//AK3/ALYH+5hX6FV5N4Y/5GHwx/vyf+iJa9ZrysPhoYVShDZu/potDmwWFhhIzhT2bv6aLQ//Z';
        }else{
            target.dataset.count = count + 1;
            target.src = '//xxx/default.jpg';
        }
    }
},true)

Guess you like

Origin blog.csdn.net/weixin_44727080/article/details/113347346