I have got a web app written in React js in which I need to integrate a javascript SDK as documented in this link
The sample code is:
<script type="text/javascript">
var _user_id = 'al_capone'; // Set to the user's ID, username, or email address, or '' if not yet known.
var _session_id = 'unique_session_id'; // Set to a unique session ID for the visitor's current browsing session.
var _sift = window._sift = window._sift || [];
_sift.push(['_setAccount', 'INSERT_BEACON_KEY_HERE']);
_sift.push(['_setUserId', _user_id]);
_sift.push(['_setSessionId', _session_id]);
_sift.push(['_trackPageview']);
(function() {
function ls() {
var e = document.createElement('script');
e.src = 'https://cdn.sift.com/s.js';
document.body.appendChild(e);
}
if (window.attachEvent) {
window.attachEvent('onload', ls);
} else {
window.addEventListener('load', ls, false);
}
})();
</script>
Now, I'm aware that I should not use window object in React app however this sample code requires me to attach an object to the window object.
I have created a function to add the script:
function createSiftScript(sift_script_ele) {
//attach the object array to the window
var _sift = window._sift = window._sift || [];
_sift.push(['_setAccount', SIFT_SCIENCE_BEACON_KEY]);
_sift.push(['_setUserId', email]);
_sift.push(['_setSessionId', setUniqueSessionId()]);
//attach the external script
sift_script_ele = document.createElement("script");
sift_script_ele.setAttribute('id', SIFT_SCRIPT_ID);
sift_script_ele.setAttribute('type', "text/javascript");
sift_script_ele.setAttribute('src', "https://cdn.sift.com/s.js");
document.head.appendChild(sift_script_ele);
}
And a function to set the object on the window as suggested for SPAs like mine build in React/Angular:
export function pushEventsToSift() {
_sift.push(['_trackPageview']);
}
I'll call these functions in all the pages wherever needed however, accessing the window object looks dirty to me.
My question is:
If you would be doing this SDK integration in a React SPA then how would you have approached it by following the cleanest approach?