rraja rraja
rraja rraja

Reputation: 23

JavaScript redirect while passing on the parameter to new URL

Im trying to write the code for a javascript that will redirect to a new url while fetching the url parameter and passing it to the new url.

The visited url = www.example.com/files/?id=12345

New Url to redirect to = www.sample.com/files/?list=12345

This is the below code i have been able to come up with.

<!DOCTYPE html>
<html>
<body>

<script>
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

window.location.href = `www.sample.com/files/?list=${id}`;

</script>

</body>
</html>

Upvotes: 1

Views: 912

Answers (1)

Daniel Cruz
Daniel Cruz

Reputation: 2295

your code works well, but when using window.location.href to redirect, the browser by default asumes that the url you are using is relative to the current site, so if you redirect to "sample.com" you are going to end up in "example.com/sample.com"

So to force the browser to redirect to another site you need to include the full URL with the protocol "https://sample.com"

So the fixed code would be

<!DOCTYPE html>
<html>
<body>

<script>
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

window.location.href = `https://www.sample.com/files/?list=${id}`;

</script>

</body>
</html>

Note that Im using https, if your site does not have https, change it for http or you are gonna get an error from the browser (and try to get https jeje)

Upvotes: 1

Related Questions