0

I want to redirect user to a specific page, when they are not on this page.

So something like (pseudo code):

if not (url = example.com/index.php)
   redirect to example.com/index.php
/if

When a user e.g. visit page example.com/forum.php he will be redirected to example.com/index.php

(The jQuery file is loaded in every file)

How can I archive that?

Zoker
  • 2,020
  • 5
  • 32
  • 53
  • 2
    Check window.location... https://developer.mozilla.org/en-US/docs/Web/API/Window.location – Hugo Dozois Sep 27 '14 at 14:50
  • possible duplicate of [How can I check if one string contains another substring in JavaScript?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring-in-javascript) – Friso Kluitenberg Sep 27 '14 at 14:50

2 Answers2

3

You can use window.location.href. Example here...

if(url === 'example.com/forum.php'){
    window.location.href = 'example.com/index.php';
    return False;
}

Don't forget to use return false at the end of the block so that if there are any runnable code after the window.location.href, then browser can ignore that

andyrandy
  • 72,880
  • 8
  • 113
  • 130
MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • Yes that works, but I figured out, that the url === does not work for me: Uncaught ReferenceError: url is not defined – Zoker Sep 27 '14 at 15:16
2

To elaborate further, since I cannot comment...url will return undefined without first defining it (you will notice Zoker's comment above).

To define url, you can do this:

var url = $(location).attr('href');

Then you can proceed to perform the check:

if(url === 'yourspecifiedurl.com'){
     window.location.href = 'yournewurl.com';
     return false;
}

Additionally, you do not need to use window.location.href as window.location will suffice. It defaults to window.location.href

A final thought, you can also use replace:

window.location.replace('theurltodirectto.com');