I would like to update a parameter of a URL so in node JS I have a code that works fine see below:
var injectCorrectIndexKey = function (url) {
var href = new URL(url);
href.searchParams.set('key', 'ZZZZZZZ');
return href.toString();
};
var x = 'https://mywebsite.com?key=7E27728B15&name=%20CORP';
console.log(injectCorrectIndexKey(x));
I tried to run the same code with CasperJS as following :
var injectCorrectIndexKey = function (url) {
var href = new URL(url);
href.searchParams.set('key', 'ZZZZZZZ');
return href.toString();
};
casper.start("https://google.com").then(function () {
var x = 'https://mywebsite.com?key=7E27728B15&name=%20CORP';
casper.echo((injectCorrectIndexKey(x));
});
I'm getting this error:
[debug] [phantom] url changed to "https://www.google.com/#spf=1637428890238"
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[info] [phantom] Step anonymous 3/3 https://www.google.com/#spf=1637428890238 (HTTP 200)
TypeError: undefined is not an object (evaluating 'href.searchParams.set')
/var/www/phantomjs:/code/test.js:37 in injectCorrectIndexKey
/var/www/phantomjs:/code/test.js:42
/var/www/phantomjs:/platform/casper.js:1685 in runStep
/var/www/phantomjs:/platform/casper.js:414 in checkStep
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "about:blank"
Why is href.searchParams.set not working when I run it inside CasperJS? Isn't it valid JS code? Any idea please why it is not working as expected?
Thanks.
I solved my issue using this function to replace parameters.
var injectCorrectIndexKey = function (url, paramName, paramValue) {
if (paramValue === null) {
paramValue = '';
}
var pattern = new RegExp('\\b(' + paramName + '=).*?(&|#|$)');
if (url.search(pattern) >= 0) {
return url.replace(pattern, '$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/, '');
return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
};