Best way to add query param to all navigations - javascript

I am looking for a solution to add query param on each URL after navigation using WebDriverIO.
For example:
Base URL: https://www.google.com/?block=true
When I click a button on the page loaded from the above URL, new URL that loads is https://www.google.com/search-page.
I would like to append ?block=true to all the navigations.
For the base URL, I can use the method browser.url("https://www.google.com/?block=true"). Not sure how I can add to other pages that are navigated using click actions.

You can use URLSearchParams to generate complex search params. Check out the below example.
const baseUrl = "https://www.google.com/?block=true"; // window.location.href
const searchUrl = "https://www.google.com/search?test=testparam";
function getRedirectUrl(baseUrl, newUrl) {
let oldParms = new URL(baseUrl).searchParams;
const newUrlParams = new URL(newUrl).searchParams;
for(let [value, key] of oldParms.entries()){
newUrlParams.append(key, value);
}
const newSearch = new URL(newUrl).search;
return `${newUrl.slice(0, -1 * newSearch.length)}?${newUrlParams.toString()}`;
}
console.log(getRedirectUrl(baseUrl, searchUrl));

Related

How to get url parameters with same name from URL in js?

For example I have this url
https://www.test.com/test.html?categoryid=4&test1=12&test2=65&brand[0]=val1&brand[1]=val2&test3=15
Now how do I get value of brand[0]=val1&brand[1]=val2 but it can be any number of there in the url maybe brand[2],brand[3] etc... or none url can be without this parameter
I need to get if brand parameter is in url and if yes then I need to get all which are availabe in the url
Any help would be great!
So you don't really know if there would be parameters or not so that's why I can propose this solution right here it will parse all your parameters anyways and stack them in the config JSON in case there is no parameters config would be empty then on your DOMloaded event you can handle the cases as you want
const config = {};
const loadConfig = () => {
const urlQuery = new URLSearchParams(window.location.search);
urlQuery.forEach((e, k) => {
config[k] = e;
});
};
const onLoadEvent = () => {
console.log(config) // should contain all the query string params.
}

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 extract id parameter from an URL using reactjs

http://localhost:3000/messages/?qr_asset_id=1f6b997464&gts=1627828213
this is an URL, I need to extract the qr_asset_id value from this URL
how do I do this with reactjs
As you're using hooks based on your used tags:
const location = useLocation();
const urlParams = new URLSearchParams(location.search);
const paramValue = urlParams.get('qr_asset_id');
You pull it from the props. props.match.params.qr_asset_id
You can use URLSearchParams.
check for browser compatibility first
const url = window.location.href // "http://localhost:3000/messages/?qr_asset_id=1f6b997464&gts=1627828213";
const searchParams = new URLSearchParams(url);
const qrAssetId = searchParams.get("qr_asset_id"); // 1f6b997464
query parameter guide in react-router should help.
There are url-polyfill libraries out there too. You can use them to get the same result.
url-polyfill
whatwg-url

how to pass multiple parameters to the web API?

I want to send something like this to API
/GetRegionsByParentIdAndRegionType?parentId=63&regionTypeEnum=5
This is the method I use
return Service.get("/GetRegionsByParentIdAndRegionType?parentId= & regionTypeEnum=" +params.parentId+ params.regionTypeId, (status, data) => {
callback(status, data);
});
I know this is wrong.
What is the right way to use it?
Use the URL constructor to create an instance of URL and then append the search parameters using URL.searchParams property.
Following snippet shows a simple example:
const url = new URL('https://example.com');
url.searchParams.append('parentId', 63);
url.searchParams.append('regionTypeEnum', 5);
console.log(url);
Alternatively, you could create an instance of URLSearchParams and then concatenate that with the URL string.
Following code snippet shows an example:
let str = '/GetRegionsByParentIdAndRegionType?';
const searchParams = new URLSearchParams();
searchParams.append('parentId', 63);
searchParams.append('regionTypeEnum', 5);
str += searchParams;
console.log(str);

Categories

Resources