I want to visit https://example.com/?GCLID=test123 and store whatever is in GCLID in a variable.
How do I do this? The following keeps returning null
JavaScript
x
10
10
1
var url = window.location.href;
2
3
// test
4
url = "https://example.com/?GCLID=test123";
5
6
const params = new URLSearchParams(url);
7
var gclid = params.get('GCLID');
8
9
alert(params);
10
alert(gclid);
Advertisement
Answer
You have to take the part after ‘?’ in new URLSearchParams, see below example for same, i.e you will pass window.location.search like this
JavaScript
1
2
1
const params = new URLSearchParams(window.location.search);
2
JavaScript
1
10
10
1
var url = window.location.href;
2
3
// test
4
url = "https://example.com/?GCLID=test123";
5
6
const params = new URLSearchParams(url.split('?')[1]);
7
var gclid = params.get('GCLID');
8
9
alert(params);
10
alert(gclid);