window.onerror 错误监听,发到后台

var doc = document.body || document.documentElement;

var _onerror = Onerror('');
var Onerror = function(url){
	this.init(url);
}
Onerror.prototype.init = function(url){
	this.url = url;
	this.system = this._system();
    this.browser = this._browser();
    this.host = location.host;
    this.referrer = document.referrer;
    this.path = location.pathname;
}
Onerror.prototype._system = function(){
	return navigator.platform || "UNKNOW"; 
}
Onerror.prototype._browser = function (){
    return navigator.userAgent || "UNKNOW";
};



Onerror.prototype.catchError = function ( des, path, line, word ){
    if( !des ) return false;
    return this.request({
        description : des,
        file : path,
        line : line,
        word : word
    });
};
Onerror.prototype.request = function ( url, options ){

    var self = this;
    var default_settings = {
        "host" : self.host,
        "referrer" : self.referrer,
        "path" : self.path,
        "timestamp" : +new Date,
        "system" : self.system,
        "browser" : self.browser,
        "language" : self.language
    };
    //beacon使用post方式
    //img_beacon使用get方式
    this[ ( isSupportBeacon && openBeacon ) ? "_beacon" : "_img_beacon" ]( url, $.extend( default_settings, options ));
};
Onerror.prototype._beacon = function ( url, options ){
    return navigator.sendBeacon( url, JSON.stringify( options ));
};

Onerror.prototype._img_beacon = function ( url, options ){
   var img = new Image();
   img.src = url + "?" + Object2URLString( options );
   img.onload = function (){};
   return doc.appendChild( img );
};
function Object2URLString ( obj ){
    var r = [];
    for( var i in obj ){
        r.push( i + "=" + obj[i] );
    }
    return r.join("&");
}

window.onerror = function (){
    return _onerror.catchError(arguments);
};

  node express 代码

router.get('/window-onerror/error.gif', function(req, res, next) {
  var $req = getData(req),
            data = $req.result,
            isBeacon = $req.isBeacon;
        if (!data.utmb) {
            return this.res.end();
        }
        //insert database
        console.log(data);
        //beacon 无需返回值
        if (isBeacon) {
            return res.end();
        }
        //img beacon
        else {
            //设置http请求头为image/gif
            res.writeHead('200', {'Content-Type': 'image/gif'});
            //1x1 的 gif图为返回值
            return res.end('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==', 'base64');
        }
});

  

 

转载于:https://www.cnblogs.com/shenggen/p/5104909.html

你可能感兴趣的:(window.onerror 错误监听,发到后台)