Location API
The Location API contains functionality for working with a page's URL and for navigating visitors to other pages.
Let's take a look at some of the functionality that's available in the Location API.
Query Parameters
There are many situations where you might want to read query parameters from a page's URL or to edit the query parameters in the URL.
For example, you might want to send information between pages using query parameters. Or you might want to update the query parameters on a page that displays dynamic content to reflect the current content shown on the page.
Reading Query Parameters
To read query parameters from a URL, use the query
property. The query
property returns an object where the keys of the object are the keys in the URL's query string and the values in the object are the corresponding values in the query string.
For example, let's say you have a URL like this:
Copy Codewww.mysite.com/page?key1=value1&key2=value2
You can retrieve the query parameters like this:
javascript | Copy Codeconst query = wixLocation.query;
The query
variable will then contain the following object:
javascript | Copy Code{ key1: "value1", key2: "value2" }
Editing Query Parameters
To edit the query parameters of a URL, use the queryParams
property. The queryParams
property returns an object with functions for adding and removing query parameters.
The add()
function adds new key:value pairs to the query string or replaces existing ones. You call the function by passing an object that contains the key:value pairs you want to add or update.
So, if you start with a URL like this:
Copy Codewww.mysite.com/page?key1=value1&key2=value2
Then, you call the add()
function like this:
javascript | Copy CodewixLocation.queryParams.add({ key2: "new2", key3: "value3" });
The URL will look this this:
Copy Codewww.mysite.com/page?key1=value1&key2=new2&key3=value3
As you can see, the following occurs:
- The value for
key1
remains the same since it was not included in the object passed to theadd()
function. - The value for the original
key2
is replaced by the new value passed to theadd()
function. - The key
key3
and its value are added becausekey3
did not exist in the original URL.
The remove()
function removes existing key:value pairs from the query string. You call the function by passing an array of the keys you want to remove.
So, if you start with a URL like this:
Copy Codewww.mysite.com/page?key1=value1&key2=value2&key3=value3
Then call the remove()
function like this:
javascript | Copy CodewixLocation.queryParams.remove(["key1", "key3"]);
The URL will look this this:
Copy Codewww.mysite.com/page?key2=value2
Was this helpful?