JQuery Detect If in Homepage and Homepage PLUS url Variables
Asked Answered
B

6

28

I am using this code to detect the homepage and it works great:

var url= window.location.href;
if(url.split("/").length>3){
    alert('You are in the homepage');
}

My problem is that I also need to detect if the url has variables for example:

mysite.com?variable=something

I need to also detect if the url has variables on it too

How can I do this?

Bunton answered 24/6, 2013 at 8:31 Comment(0)
A
6

Take a look at the window.location docs , the information you want is in location.search , so a function to check it could just be:

function url_has_vars() {
   return location.search != "";
}
Abadan answered 24/6, 2013 at 8:34 Comment(0)
A
81

Using window.location.pathname could work too:

if ( window.location.pathname == '/' ){
    // Index (home) page

} else {
    // Other page
    console.log(window.location.pathname);
}

See MDN info on window.location.pathname.

Aquilar answered 22/4, 2015 at 4:48 Comment(2)
if ( window.location.pathname == '/' || window.location.pathname == '/index.php'){ // your stuff }Psychotic
perfect !! ThanksRenayrenckens
K
15

You can find out if you're on the homepage by comparing href to origin:

window.location.origin == window.location.href

To get the query parameters you can use the answer here: How can I get query string values in JavaScript?

Keynote answered 24/6, 2013 at 8:34 Comment(2)
I noticed that href can return the url with a trailing slash, eg mysite.com/ , while origin is without a slash...Sorcim
This answer is wrong: it fails because window.location.origin is http://www.mywebsite.com while window.location.href is http://www.mywebsite.com/Paraphrase
A
6

Take a look at the window.location docs , the information you want is in location.search , so a function to check it could just be:

function url_has_vars() {
   return location.search != "";
}
Abadan answered 24/6, 2013 at 8:34 Comment(0)
H
3

if current url is xxxxx.com something like that, then xxx

if (window.location.href.split('/').pop() === "") { 
    //this is home page
}
Hulen answered 4/8, 2017 at 5:34 Comment(0)
B
2

You need a query string searching function to do this..

function getParameterByName(name) {  
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");  
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),  
        results = regex.exec(location.search);  
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));  
}

Before redirect check the query string and match with the expected value and redirect as requirement.

Blaze answered 24/6, 2013 at 8:38 Comment(0)
B
1

Taking inspiration from Mataniko suggestion, I slightly modified it to fix its issue:

if (window.location.origin + "/" == window.location.href ) {
  // Index (home) page
  ...
}

In this way, this test pass only in homepage

Basia answered 3/7, 2020 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.