Editing the question as StackOverflow doesn’t like what I posted.
I am working on building a script that will check the URL being loaded for a parameter and if the parameter doesn’t exist, add it. The URL that is being loaded is https://www.{domain}.org/Dashboard.aspx
This part is working based on my code below but the problem is that I can’t seem to get it to see the parameter and not add the code. I have a user who logs in and loads the page via a back-end query list and it loads the page with the code of the entity he wants to see but because of the scripting below, it adds an additional code from his record so he can only ever see his record and no one else’s. I know this is an If...then...else
statement but everything I have tried doesn’t work.
Can someone help? Just to note, this is a website connected to our agency database so I am pulling information from the database so you will see in my example below, I add {code from database}
Existing Code:
let url = window.location.href;
if (url.indexOf("' + {code from database} + '") <= -1)
{
window.location.search += "&Code=' + {code from database} + '";
}
End user who is having the problem loads the page from a query list and the page loads like this for him: https://www.{domain}.org/Dashboard.aspx?Code=X123?Code=Y355
This page is hit two different ways. From within the database interface itself where when you click on the record, it loads the page with the code in it already (this is how this user is accessing it) and then from their website clicking on a link and if the end user who is signed in is part of a security group, the page loads and adds said code to the URL but they are loading the URL like this: Https://www.{domain}.org/dashboard.aspx and the script is adding the code from their profile
Hopefully, this makes sense and if not, let me know.
4
First what you need is to parse the URL using URL object
learn more about URL
let url = new URL(window.location.href);
then you dont need to check if the code is passed to the searchParams
you only need to check for the key if its exists or not.
let url = new URL(window.location.href);
if (!url.searchParams.has("Code")) {
url.searchParams.set("Code", codeFromDatabase);
window.location.search = url.search;
}
also important to mention that you don’t need if statement
because if the Code
key or value did not changed then window.location.search = url.search;
will not redirect or refresh the page with new changes, therefor you can do this.
let url = new URL(window.location.href);
url.searchParams.set("Code", codeFromDatabase);
window.location.search = url.search;
4