I have here a function that checks each parameters in the url and store it as cookie. But I have a problem, whenever I pass those parameter entered into a new url using XMLHttpRequest() it returns only the first parameter entered from the user.
Here my javascript code:
<!-- Get Parameters for gclid, token , fbclid or cjevent when user visits the website -->
<script>
window.onload = function() {
try {
var url_string = (window.location.href).toLowerCase();
var url = new URL(url_string);
// check parameters if exists
['gclid', 'token', 'fbclid', 'cjevent'].forEach(function (key) {
var value = url.searchParams.get(key);
if (value) {
//token expires in 6 hours
document.cookie = `${key}=${value}; max-age=21600` + ';path=/';
}
});
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
// Sending a get request to laravel controller
var base_url = window.location.origin; // get the base url
var params = '';
// pass parameters if gclid, token, or fbclid
if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');}
else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');}
else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');}
else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');}
// send those parameters in TrafficTracking Controller storeTracking function
let xhr = new XMLHttpRequest();
xhr.open("GET", base_url+"/storetrackvisit?"+params, true);
xhr.send();
} catch (err) {
console.log("Issues with Parsing URL Parameter's - " + err);
}
}
</script>
When I try to use the alert() function in the var params it returns only the first parameter that user has entered.
For example:
1.) User enters test.com?gclid=111 -> stores that as a cookie
2.) user re enters another value for other parameter test.com?token=551 -> it will still alert the gclid parameter
How do I refactor my if-else condition that returns only the parameter when a user enters it and assign it in the params variable.
I believe this is something to do with this code:
if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');}
else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');}
else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');}
else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');}
alert(params);
How can I modify my if-else conditions to return only the parameters what user entered? I believe that what I've done it fetches the last cookie saved.
Aucun commentaire:
Enregistrer un commentaire