Current JavaScript URL Checker

I am wondering how to get JavaScript to check if a user is at a specific URL, so I can build an if statement from the result.

My reasoning is that if the user clicks on the link in the menu and they are currently located on truck.php, javascript redirects them to a specific page. If they are not on truck.php, they will be redirected to another page.

Greetings guys.

+4
source share
3 answers

The current location is in location.href .

The location object also contains some other useful fields:

  • location.hash: part after # in URL
  • location.host: hostname, including port (if specified)
  • location.hostname: just the host name
  • location.pathname: requested URI without protocol / host / port; beginning with /
  • location.port: Port - only if specified in the URL
  • location.protocol: Usually "http:" or "https:" is the mind at the end of the colon

In your case, the most fault tolerant way is to check if filename truck.php is:

 var parts = location.pathname.split('/'); if(parts[parts.length - 1] == 'trucks.php') { location.href = 'some-other-page'; } 

If you want to redirect without saving the current page in history, use the following code instead of assigning location.href :

 location.replace('some-other-page'); 
+9
source

Use window.location.href to get the current URL, or window.location.pathname to get only the path. For your specific problem, the solution only requires a path name:

 if (window.location.pathname == "/trucks.php") window.location = "/somewhereelse.php"; 

View the MDC documentation for window.location .

+4
source

Use window.location

0
source

All Articles