docbrown/app/assets/javascripts/initializers/initializeBodyData.js
Jeremy Schuurmans 96eb1a070a Fix ESLint errors in initializeBodyData.js (#4267)
* fix use global form of use strict error

* fix errors involving functions being used before being defined

* fix undefined function and == errors

* fix redeclared variable name error

* use arrow functions to fix unnamed function warnings

* specify global function at top of file instead of disabling line in eslint, change meta variable name
2019-10-10 13:17:16 -04:00

55 lines
1.8 KiB
JavaScript

'use strict';
/* global checkUserLoggedIn */
function removeExistingCSRF() {
var csrfTokenMeta = document.querySelector("meta[name='csrf-token']");
var csrfParamMeta = document.querySelector("meta[name='csrf-param']");
if (csrfTokenMeta && csrfParamMeta) {
csrfTokenMeta.parentNode.removeChild(csrfTokenMeta);
csrfParamMeta.parentNode.removeChild(csrfParamMeta);
}
}
function fetchBaseData() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xmlhttp.responseText);
if (json.token) {
removeExistingCSRF();
}
var newCsrfParamMeta = document.createElement('meta');
var metaTag = document.querySelector("meta[name='csrf-token']");
newCsrfParamMeta.name = 'csrf-param';
newCsrfParamMeta.content = json.param;
document.getElementsByTagName('head')[0].appendChild(newCsrfParamMeta);
var newCsrfTokenMeta = document.createElement('meta');
newCsrfTokenMeta.name = 'csrf-token';
newCsrfTokenMeta.content = json.token;
document.getElementsByTagName('head')[0].appendChild(newCsrfTokenMeta);
document.getElementsByTagName('body')[0].dataset.loaded = 'true';
if (checkUserLoggedIn()) {
document.getElementsByTagName('body')[0].dataset.user = json.user;
browserStoreCache('set', json.user);
setTimeout(() => {
if (typeof ga === 'function') {
ga('set', 'userId', JSON.parse(json.user).id);
}
}, 400);
}
}
};
xmlhttp.open('GET', '/async_info/base_data', true);
xmlhttp.send();
}
function initializeBodyData() {
fetchBaseData();
}