// Set global vars var CSRFToken = "c4fa2c2bc9936b70dcbd3bf22a103e595cab76e28a0a12b55f6dd4930b265caf"; var $xo = jQuery.noConflict(); var $jq = $xo; if (delete $) { $ = $xo; } else { var $ = $xo; // Previously defined with var } // Register jquery vars to add CSRF headers to ajax() calls setSpecificRequestHeader("$xo"); setSpecificRequestHeader("$jq"); setSpecificRequestHeader("$"); setSpecificRequestHeader("jQuery"); // Add CSRF headers to all jQuery ajax() calls that start with '/api/v[0-9]/'. function setSpecificRequestHeader(jqtype) { if (typeof window[jqtype] == 'function') { window[jqtype](document).ajaxSend(function( event, request, settings ) { var urlinfo = new URL(settings.url, window.location.href); // Parse the url (based off of the current url if relative) if (urlinfo.hostname == window.location.hostname && /^\/api\/v[0-9]\//.test(urlinfo.pathname)) { // Add the CSRF token to all XO API calls request.setRequestHeader("X-CSRFToken", CSRFToken); } }); } } // Re-apply the CSRF addition to "$" any time a new jQuery is added to the site function reapplyCSRFSetup() { setSpecificRequestHeader("$"); } // Observe any DOM changes that attempt to add a new jquery script // If found, re-apply CSRF setup var xoObserver = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (node) { if (node.tagName && node.tagName.toLowerCase() === 'script' && node.src) { // Match only scripts that look like the actual jQuery library var regex = /jquery(?:\.min)?(?:-\d+\.\d+\.\d+)?\.js(\?.*)?$/i; if (regex.test(node.src)) { // Check for an existing onload handler if (node.onload) { var originalOnLoad = node.onload; node.onload = function () { originalOnLoad.apply(this); // Call original onload reapplyCSRFSetup.apply(this); // Reapply CSRF setup when a new jQuery script is added }; } else { node.onload = reapplyCSRFSetup; // Reapply CSRF setup when a new jQuery script is added } } } }); }); }); xoObserver.observe(document.documentElement, { childList: true, subtree: true });