Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch support when XMLHttpRequest isn't available #342

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 98 additions & 32 deletions dist/mixpanel.amd.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ define(function () { 'use strict';
var hasOwnProperty = ObjProto.hasOwnProperty;
var windowConsole = window$1.console;
var navigator = window$1.navigator;
var document$1 = window$1.document;
var document = window$1.document;
var windowOpera = window$1.opera;
var screen = window$1.screen;
var userAgent = navigator.userAgent;
Expand Down Expand Up @@ -978,7 +978,7 @@ define(function () { 'use strict';
_.cookie = {
get: function(name) {
var nameEQ = name + '=';
var ca = document$1.cookie.split(';');
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
Expand Down Expand Up @@ -1009,7 +1009,7 @@ define(function () { 'use strict';
if (domain_override) {
cdomain = '; domain=' + domain_override;
} else if (is_cross_subdomain) {
var domain = extract_domain(document$1.location.hostname);
var domain = extract_domain(document.location.hostname);
cdomain = domain ? '; domain=.' + domain : '';
}

Expand All @@ -1027,7 +1027,7 @@ define(function () { 'use strict';
secure += '; secure';
}

document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
},

set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
Expand All @@ -1036,7 +1036,7 @@ define(function () { 'use strict';
if (domain_override) {
cdomain = '; domain=' + domain_override;
} else if (is_cross_subdomain) {
var domain = extract_domain(document$1.location.hostname);
var domain = extract_domain(document.location.hostname);
cdomain = domain ? '; domain=.' + domain : '';
}

Expand All @@ -1055,7 +1055,7 @@ define(function () { 'use strict';
}

var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
document$1.cookie = new_cookie_val;
document.cookie = new_cookie_val;
return new_cookie_val;
},

Expand Down Expand Up @@ -1257,21 +1257,21 @@ define(function () { 'use strict';

function getElementsBySelector(selector) {
// Attempt to fail gracefully in lesser browsers
if (!document$1.getElementsByTagName) {
if (!document.getElementsByTagName) {
return [];
}
// Split selector in to tokens
var tokens = selector.split(' ');
var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;
var currentContext = [document$1];
var currentContext = [document];
for (i = 0; i < tokens.length; i++) {
token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
if (token.indexOf('#') > -1) {
// Token is an ID selector
bits = token.split('#');
tagName = bits[0];
var id = bits[1];
var element = document$1.getElementById(id);
var element = document.getElementById(id);
if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
// element not found or tag with that ID not found, return false
return [];
Expand Down Expand Up @@ -1418,7 +1418,7 @@ define(function () { 'use strict';
kw = '',
params = {};
_.each(campaign_keywords, function(kwkey) {
kw = _.getQueryParam(document$1.URL, kwkey);
kw = _.getQueryParam(document.URL, kwkey);
if (kw.length) {
params[kwkey] = kw;
}
Expand Down Expand Up @@ -1599,8 +1599,8 @@ define(function () { 'use strict';
return _.extend(_.strip_empty_properties({
'$os': _.info.os(),
'$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
'$referrer': document$1.referrer,
'$referring_domain': _.info.referringDomain(document$1.referrer),
'$referrer': document.referrer,
'$referring_domain': _.info.referringDomain(document.referrer),
'$device': _.info.device(userAgent)
}), {
'$current_url': window$1.location.href,
Expand All @@ -1626,7 +1626,7 @@ define(function () { 'use strict';
pageviewInfo: function(page) {
return _.strip_empty_properties({
'mp_page': page,
'mp_referrer': document$1.referrer,
'mp_referrer': document.referrer,
'mp_browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
'mp_platform': _.info.os()
});
Expand Down Expand Up @@ -4055,11 +4055,12 @@ define(function () { 'use strict';
// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
// https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
var USE_XHR = (window$1.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
var USE_FETCH = !_.isUndefined(fetch) && typeof(fetch) === 'function'

// IE<10 does not support cross-origin XHR's but script tags
// with defer won't block window.onload; ENQUEUE_REQUESTS
// should only be true for Opera<12
var ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);
var ENQUEUE_REQUESTS = !USE_XHR && !USE_FETCH && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);

// save reference to navigator.sendBeacon so it can be minified
var sendBeacon = null;
Expand Down Expand Up @@ -4276,7 +4277,7 @@ define(function () { 'use strict';
}
});
window$1.addEventListener('visibilitychange', function() {
if (document$1['visibilityState'] === 'hidden') {
if (document['visibilityState'] === 'hidden') {
flush_on_unload();
}
});
Expand Down Expand Up @@ -4309,12 +4310,12 @@ define(function () { 'use strict';

// update persistence with info on referrer, UTM params, etc
MixpanelLib.prototype._set_default_superprops = function() {
this['persistence'].update_search_keyword(document$1.referrer);
this['persistence'].update_search_keyword(document.referrer);
if (this.get_config('store_google')) {
this['persistence'].update_campaign_params();
}
if (this.get_config('save_referrer')) {
this['persistence'].update_referrer_info(document$1.referrer);
this['persistence'].update_referrer_info(document.referrer);
}
};

Expand Down Expand Up @@ -4362,7 +4363,7 @@ define(function () { 'use strict';
return null;
}

if (USE_XHR) {
if (USE_XHR || USE_FETCH) {
var callback_function = function(response) {
callback(response, data);
};
Expand Down Expand Up @@ -4402,7 +4403,7 @@ define(function () { 'use strict';
options = null;
}
options = _.extend(DEFAULT_OPTIONS, options || {});
if (!USE_XHR) {
if (!USE_XHR && !USE_FETCH) {
options.method = 'GET';
}
var use_post = options.method === 'POST';
Expand All @@ -4415,7 +4416,7 @@ define(function () { 'use strict';
if (this.get_config('test')) { data['test'] = 1; }
if (verbose_mode) { data['verbose'] = 1; }
if (this.get_config('img')) { data['img'] = 1; }
if (!USE_XHR) {
if (!USE_XHR && !USE_FETCH) {
if (callback) {
data['callback'] = callback;
} else if (verbose_mode || this.get_config('test')) {
Expand All @@ -4439,9 +4440,9 @@ define(function () { 'use strict';

var lib = this;
if ('img' in data) {
var img = document$1.createElement('img');
var img = document.createElement('img');
img.src = url;
document$1.body.appendChild(img);
document.body.appendChild(img);
} else if (use_sendBeacon) {
try {
succeeded = sendBeacon(url, body_data);
Expand Down Expand Up @@ -4525,13 +4526,78 @@ define(function () { 'use strict';
lib.report_error(e);
succeeded = false;
}
} else if (USE_FETCH) {
try {
var headers = this.get_config('xhr_headers');
if (use_post) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}

var fetchOpts = {
method: options.method,
mode: 'cors',
credentials: 'include',
headers: headers,
body: body_data
};

fetch(url, fetchOpts)
.then(function (response) {
return response.text().then(function (body) {
return {
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: body
};
});
})
.then(function (res) {
if (res.status === 200) {
if (callback) {
var body = res.body;
if (verbose_mode) {
var response;
try {
response = _.JSONDecode(body);
} catch (e) {
lib.report_error(e);
if (options.ignore_json_errors) {
response = body;
} else {
return;
}
}
callback(response);
} else {
callback(Number(body));
}
}
} else {
var error = 'Bad HTTP status: ' + res.status + ' ' + res.statusText;
lib.report_error(error);

if (callback) {
if (verbose_mode) {
var xhr_req = { status: res.status, responseHeaders: res.headers };
callback({ status: 0, error: error, xhr_req: xhr_req });
} else {
callback(0);
}
}
}
});
} catch (e) {
lib.report_error(e);
succeeded = false;
}
} else {
var script = document$1.createElement('script');
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = url;
var s = document$1.getElementsByTagName('script')[0];
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
}

Expand Down Expand Up @@ -4968,7 +5034,7 @@ define(function () { 'use strict';
*/
MixpanelLib.prototype.track_pageview = function(page) {
if (_.isUndefined(page)) {
page = document$1.location.href;
page = document.location.href;
}
this.track('mp_page_view', _.info.pageviewInfo(page));
};
Expand Down Expand Up @@ -5925,7 +5991,7 @@ define(function () { 'use strict';

function do_scroll_check() {
try {
document$1.documentElement.doScroll('left');
document.documentElement.doScroll('left');
} catch(e) {
setTimeout(do_scroll_check, 1);
return;
Expand All @@ -5934,19 +6000,19 @@ define(function () { 'use strict';
dom_loaded_handler();
}

if (document$1.addEventListener) {
if (document$1.readyState === 'complete') {
if (document.addEventListener) {
if (document.readyState === 'complete') {
// safari 4 can fire the DOMContentLoaded event before loading all
// external JS (including this file). you will see some copypasta
// on the internet that checks for 'complete' and 'loaded', but
// 'loaded' is an IE thing
dom_loaded_handler();
} else {
document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
document.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
}
} else if (document$1.attachEvent) {
} else if (document.attachEvent) {
// IE
document$1.attachEvent('onreadystatechange', dom_loaded_handler);
document.attachEvent('onreadystatechange', dom_loaded_handler);

// check to make sure we arn't in a frame
var toplevel = false;
Expand All @@ -5956,7 +6022,7 @@ define(function () { 'use strict';
// noop
}

if (document$1.documentElement.doScroll && toplevel) {
if (document.documentElement.doScroll && toplevel) {
do_scroll_check();
}
}
Expand Down
Loading