I am trying to get the url query string parameters from current page and I have the following code:
doInit: function (component, event, helper) {
var urlParams = new URLSearchParams(window.location.search);
console.log("params::: ", urlParams);
if (urlParams.has("openSidebar") && urlParams.get("openSidebar") == true) {
console.log("redirection happening....");
component.set("v.showFeed", true);
component.set("v.isSidebarOpen", true);
}
},
for some reason seems that I cannot use this line var urlParams = new URLSearchParams(window.location.search); and I dont know why.
Are there any alternative or salesforce way hwo to get the query string parameters from url?
I am basically getting nothing, the execution seems to stop at the line where I am using URLSearchParams!
Also curious to know why does lightning does not let plain javascript to execute in this case?
Using new URLSearchParams
will return an instance of a class, not an object (or map).
You can use this code to convert the key/pair values into an object. Then you can check the value on the object instead:
const searchParams = new URLSearchParams('?openSidebar=true&foo=bar&test=hello%26world')
const params = [...searchParams.entries()].reduce((a, [k, v]) => (a[k] = v, a), {})
console.log(params)
if (params.openSidebar === 'true') {
console.log("redirection happening....");
// do stuff here
}
Note, we use
=== 'true'
since the url parameter will always be a type of string.
Since you said it wasn't working, you could build your own parser:
const qs = '?openSidebar=true&foo=bar&test=hello%26world'
.slice(1) // remove '?'
const d = decodeURIComponent // used to make it shorter, replace d with decodeURIComponent if you want
const params = qs
.split('&') // split string into key/pair
.map(s => s.split('=')) // split key/pair to key and pair
.reduce((a, [k, v]) => ((a[d(k)] = d(v)), a), {}) // set each object prop name to k, and value to v
console.log(params)
Note, we use
decodeURIComponent()
(or shorthandd()
) last, because the parameters may contain ampersands or equals signs. Should we calld()
first, we would split on these characters, which we don't want to happen.