diff --git a/README.md b/README.md index fe57af8a..7fada804 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ ahoy.configure({ cookieDomain: null, headers: {}, visitParams: {}, + beforeSend: null, withCredentials: false, visitDuration: 4 * 60, // 4 hours visitorDuration: 2 * 365 * 24 * 60 // 2 years diff --git a/src/index.js b/src/index.js index 4421da36..c9e10397 100644 --- a/src/index.js +++ b/src/index.js @@ -13,6 +13,7 @@ let config = { cookieDomain: null, headers: {}, visitParams: {}, + beforeSend: null, withCredentials: false, visitDuration: 4 * 60, // default 4 hours visitorDuration: 2 * 365 * 24 * 60 // default 2 years @@ -170,16 +171,22 @@ function CSRFProtection(xhr) { if (token) xhr.setRequestHeader("X-CSRF-Token", token); } +function beforeSend(xhr, settings) { + CSRFProtection(xhr); + if (config.beforeSend) config.beforeSend(xhr, settings); +} + function sendRequest(url, data, success) { + let requestData = JSON.stringify(data); if (canStringify) { if ($ && $.ajax) { $.ajax({ type: "POST", url: url, - data: JSON.stringify(data), + data: requestData, contentType: "application/json; charset=utf-8", dataType: "json", - beforeSend: CSRFProtection, + beforeSend: beforeSend, success: success, headers: config.headers, xhrFields: { @@ -201,8 +208,8 @@ function sendRequest(url, data, success) { success(); } }; - CSRFProtection(xhr); - xhr.send(JSON.stringify(data)); + beforeSend(xhr, { data: requestData }); + xhr.send(requestData); } } }