Skip to content

Commit a254c14

Browse files
authored
Merge pull request #8 from tinovyatkin/master
use navigator.sendBeacon when available
2 parents 807aa8c + 48b8035 commit a254c14

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

stackdriver-errors.js

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,16 +118,23 @@
118118

119119
StackdriverErrorReporter.prototype.sendErrorPayload = function(payload, callback) {
120120
var url = baseAPIUrl + this.projectId + "/events:report?key=" + this.apiKey;
121+
var CONTENT_TYPE = 'application/json; charset=UTF-8';
122+
var payloadString = JSON.stringify(payload);
123+
var end = typeof callback === 'function' ? callback : function () {};
124+
125+
// Check if we can use sendBeacon
126+
if (typeof Blob !== 'undefined' && typeof navigator.sendBeacon === 'function') {
127+
// create blob to set content type to JSON - needed for correct HTTP header
128+
var blob = new Blob([payloadString], { type: CONTENT_TYPE });
129+
navigator.sendBeacon(url, blob);
130+
return end();
131+
}
121132

122133
var xhr = new XMLHttpRequest();
123134
xhr.open('POST', url, true);
124-
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
125-
xhr.onloadend = function() {
126-
return typeof callback === 'function' && callback();
127-
};
128-
xhr.onerror = function(e) {
129-
return typeof callback === 'function' && callback(e);
130-
};
131-
xhr.send(JSON.stringify(payload));
135+
xhr.setRequestHeader('Content-Type', CONTENT_TYPE);
136+
xhr.onloadend = end;
137+
xhr.onerror = end;
138+
xhr.send(payloadString);
132139
};
133140
})(this);

0 commit comments

Comments
 (0)