I'm wondering if Javascript can detect what page the user is on. Say for example that the user is on a "About" or "Contact" page, can JavaScript check if the pathway is "/About" or "/Contact" and then take action accordingly ? How would that code look like? I appreciate if anyone could give me a code sample
Asked
Active
Viewed 1.5k times
-5
-
1Yes, you can use `document.location.href`. – Halcyon Nov 19 '15 at 13:50
-
2`if(location.href=='/contacts')document.body.innerHTML="";` check the location, set the body html to empty string. – nicael Nov 19 '15 at 13:51
-
2When you searched on Google for "javascript get current URL", you didn't find *anything*? – David Nov 19 '15 at 13:54
-
2Look, I [googled your title](https://www.google.com/search?q=Detect%20current%20page%20with%20JavaScript) and came up with 9,640,000 results, and everything on the first page is exactly what people here are telling you to do... – Howard Renollet Nov 19 '15 at 14:00
-
2So you people who are telling OP to search, do you not know how to close questions as a duplicate? You people sound very rude to a new user here. – epascarello Nov 19 '15 at 14:02
-
it's been flagged... – Howard Renollet Nov 19 '15 at 14:03
-
@epascarello, done. But pray tell, why did you insist on answering this instead of closing as a duplicate? Surely a user with your reputation can find one quickly enough. – Frédéric Hamidi Nov 19 '15 at 17:41
2 Answers
1
If you want to know what age they are on, it really depends on the url structure. But you will get the information with window.location.pathname
var pathname = window.location.pathname;
switch(pathname) {
case "/home" :
console.log("home");
break;
case "/game" :
console.log("game");
break;
}

epascarello
- 204,599
- 20
- 195
- 236