Grab query string value from URL using Javascript - javascript

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
var url = window.location.href;
// test
url = "https://example.com/?GCLID=test123";
const params = new URLSearchParams(url);
var gclid = params.get('GCLID');
alert(params);
alert(gclid);

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
const params = new URLSearchParams(window.location.search);
var url = window.location.href;
// test
url = "https://example.com/?GCLID=test123";
const params = new URLSearchParams(url.split('?')[1]);
var gclid = params.get('GCLID');
alert(params);
alert(gclid);

Related

How to get nested query string parameter

The use case is to land on a page with a URL looking like this -
http://localhost:3000/track?url=https://somewebsite.com/?968061242&lang=EN&sign=daff4be265096eb31aca5c986ac51c6c&source=api_wrapper
I tried the following to get the query params,
let search = window.location.search;
let params = new URLSearchParams(search);
let resp = params.get('url');
console.log("resp => ", resp);
but the output I get is only up to https://somewebsite.com/?968061242
How I can also get the nested params as part of the same get method call?
Use urlencoding api of JS
Example:
const url = `http://localhost:3000/track?url=${encodeURIComponent('https://somewebsite.com/?968061242&lang=EN&sign=daff4be265096eb31aca5c986ac51c6c&source=api_wrapper')}`
let search = new URL(url).search;
let params = new URLSearchParams(search);
let resp = params.get('url');

URL transformation in Chrome javascript bookmarklet showing "undefined"

I'm trying to create a Chrome bookmarklet that will take a part of the pathname from one URL and navigate to a new URL using that variable as a parameter (the variable is 1234567 in the example below).
From: 'https://example.com/reporting-dashboard/#/dashboard/1234567?pageId=Page_3a7c73c6-34c9-4ab3-8d1f-5bd437c07115'
To: 'https://example.com/tool/permissions/resources?namespace=1234567'
The hostname differs depending on the environment I'm working in but will always stay the same when I transform it with the bookmarklet so I'm trying to pull that info when I compose the new URL. This is what I've got so far, but I keep getting "undefined" in the transformed URL (below) when I run the code. Any ideas on what I've got wrong here?
'https://example.com/tool/permissions/resources?namespace=undefined'
My code:
//Sample URL: https://example.com/reporting-dashboard/#/dashboard/1234567?pageId=Page_3a7c73c6-34c9-4ab3-8d1f-5bd437c07115
var pathArray = location.pathname.split('/');
let secondLevelLocation = pathArray[3];
var newUrl = location.protocol + '//' + location.hostname + '/tool/permissions/resources?namespace=' + secondLevelLocation;
var w=window.open();w.location=newUrl;w.document.close();
In the code you've shown, there is an assumption that the URL hash (fragment identifier) will be included when accessing the pathname:
//Sample URL: https://example.com/reporting-dashboard/#/dashboard/1234567?pageId=Page_3a7c73c6-34c9-4ab3-8d1f-5bd437c07115
var pathArray = location.pathname.split('/');
let secondLevelLocation = pathArray[3];
This is where the problem occurs. In a URL, the pathname ends when one of the following characters are first encountered:
? (which begins the query string), or
# (which begins the fragment identifier)
The format of the hash / fragment identifier portion of the URL in your example is that of a fully-resolved URL without the origin (starting at the pathname).
Using this knowledge, you can use the native URL class to help you select the desired part of the input URL, then use it again to construct the target URL, as shown in the code below. Once you have the target URL, you can use it to navigate, etc.
function parseNamespace (url) {
const fragment = url.hash.slice(1);
if (!fragment.startsWith('/')) throw new Error('Path fragment not found');
url = new URL(fragment, url);
const namespace = url.pathname.split('/').at(-1);
return namespace;
}
function createUrl (address = window.location.href) {
let url = new URL(address);
const namespace = parseNamespace(url);
const pathname = '/tool/permissions/resources';
url = new URL(pathname, url.origin);
url.searchParams.set('namespace', namespace);
return url;
}
const url = createUrl('https://example.com/reporting-dashboard/#/dashboard/1234567?pageId=Page_3a7c73c6-34c9-4ab3-8d1f-5bd437c07115');
// You can omit the argument when you want to get the address from the current document:
// const url = createUrl();
console.log(url.href); // "https://example.com/tool/permissions/resources?namespace=1234567"

How do I remove part of a string from a specific character?

I have the following url:
http://intranet-something/IT/Pages/help.aspx?kb=1
I want to remove the ?kb=1 and assign http://intranet-something/IT/Pages/help.aspx to a new variable.
So far I've tried the following:
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if(link.includes('?kb=')){
var splitLink = link.split('?');
}
However this just removes the question mark.
The 1 at the end of the url can change.
How do I remove everything from and including the question mark?
Use the URL interface to manipulate URLs:
const link = "http://intranet-something/IT/Pages/help.aspx?kb=1";
const url = new URL(link);
url.search = '';
console.log(url.toString());
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if (link.includes('?kb=')) {
var splitLink = link.split('?');
}
var url = splitLink ? splitLink[0] : link;
console.log(url);
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if(link.includes('?kb=')){
var splitLink = link.split('?');
console.log(splitLink[0]);
}
You can also try like this
const link = "http://intranet-something/IT/Pages/help.aspx?kb=1";
const NewLink = link.split('?');
console.log(NewLink[0]);

How to generate hash512 in pre-request from request that has {{variables}} in uri

So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.
I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc
I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.
I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John
I did this by :
var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));
This will return the desired result.
Here is what I logged when trying the same code with variables
console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc
All variables defined , that`s for sure
Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John
I lost source where i found it. Somewhere on postman github issue thread
var secret = pm.globals.get("devSecretKey");
pm.myUtility = {
interpolateVariable: function (str) {
return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
// console.log(match)
let result = match; //default to return the exactly the same matchd variable string
if ($1) {
let realone = pm.variables.get($1);
if (realone) {
result = realone
}
}
return result;
});
},
getUrl: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
let {
Url
} = require('postman-collection')
return new Url(url);
},
getUrlTest: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
// let {
// Url
// } = require('postman-collection')
//return new Url(url);
return pm.request.url.parse(url);
}
}
var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query
pm.environment.set("tempAuthHash", hashedPayload);// use this in your header
This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request

Removing query parameter using node.js not working

I am having this code to remove a query parameter from a url, but it is not working. Can you have a look please?
const url = require('url')
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
const link = url.format(obj)
console.log(link) // I was expecting the removal of query2 but it didn't happen
It logged the same url as was passed above, why query2 is not removed? Thanks
You need to remove search node from object
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
delete obj.search
const link = url.format(obj)
console.log(link)
This will return you url http://www.example.com/path?query1=val1
If you look at through the source for url module (https://github.com/defunctzombie/node-url/blob/master/url.js). You can see that
it will look at the search node first (line 413). Remove this as well, so that the query object is evaluated.
delete obj.search;
Even though you delete query2 from query object, query2 is still present in search field.
const url = require('url');
const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
console.log(obj);
delete obj.query.query2
delete obj.search
console.log(obj);
const link = url.format(obj)
console.log(link)
const url = require("url")
const urlObj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete urlObj.query.query2
delete urlObj.search
const newUrl = url.format(urlObj)
console.log(newUrl) // print >> http://www.example.com/path?query1=val1

Categories

Resources