Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing Javascript Redirection

Tags:

javascript

I am trying to implement what seems to be very simple JavaScript redirection, via the following rudimentary command:

window.location.href = "http://www.somesite.com";

So far so good, it works. I also can do it via the following method:

location.replace("http://www.somesite.com");

No problem here, it works again! The problem comes when I loose the protocol out of the string:

window.location.href = "www.somesite.com";

OR:

location.replace("www.somesite.com");

It just appends the new location to the current url:

www.currentsite.com/www.somesite.com

Of cause, that's not what I want. Is there any way to force the redirect?

like image 746
alexs333 Avatar asked Mar 04 '26 14:03

alexs333


2 Answers

One way is to use protocol-relative url like this:

window.location = "//www.somesite.com";

Or

window.location = "//somesite.com";

This way, it would redirect and browser itself will take care of figuring out protocol part eg http or https

Working Example

like image 64
Blaster Avatar answered Mar 07 '26 05:03

Blaster


The protocol is required.

How else would the browser know whether

location.replace("mysite.pl");

was going to a Polish website or a Perl script on the current website?

like image 27
Gareth Avatar answered Mar 07 '26 03:03

Gareth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!