Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location not replaced but concatenated

Tags:

javascript

I have this code:

$(window).ready(function() {
  var url = window.location.href;
  if (url.includes("#/projet/")) {
    projectId = url.substring(url.indexOf("#")+1).split("/").slice(2, 3).toString();
    window.location.href = "projects/" + projectId;
  };
})

I'm redirected but the window.location is not replaced, just concatenated. For instance, if my URL is localhost:3000/users/212323/dashboard, after the javascript redirection, I get localhost:3000/users/212323/projects/123456 instead of localhost:3000/projects/123456

I don't understand why the href is concatenated and not replaced, do you have an idea?

like image 286
escanxr Avatar asked Oct 27 '25 08:10

escanxr


2 Answers

window.location.href = 'someurl' works the same way as clicking that someurl in a <a> tag.

When using a relative path (i.e. without / in the beginning), your browser will concatenate the URL to the existing URL.

Simple fix in your case is to prepend the /:

window.location.href = "/projects/" + projectId;

Note though, that this will cause the site possibly not work anymore if it is moved to another location. That is why many web frameworks use full URLs and some kind of base-url to get the linking correctly.

like image 81
Bart Friederichs Avatar answered Oct 29 '25 20:10

Bart Friederichs


You need to add another / to the beginning of the url, otherwise the browser interprets the url as a relative url to the curent url.

window.location.href = "/projects/" + projectId;

The extra / at the start tells the browser to start from the root url.

like image 41
Jerodev Avatar answered Oct 29 '25 21:10

Jerodev



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!