5

I want to prevent users to navigate to URL´s that are not accessed through html element. Example:

Actually navigating on: myweb.com/news

And I want to navigate to myweb.com/news?article_id=10 by writing this in the browser navigation bar to avoid pressing any element (like <a>).

When the user writes myweb.com/news?article_id=10 in the browser url, at the moment he presses enter, the browser should not allow him to navigate to the url.

I have tried:

//This wont work since jquery does not support it
$(window.location.href).on('change', function() {
    //Here check if href contains '?'
    alert("Not allowed");
});

//Neither works, doesnt do anything
$(window).on('change', function() {
    alert("Not allowed");
});

References: there is something similar asked here On - window.location.hash - Change?, but im interested in the 'parameter' version of that question.

Community
  • 1
  • 1
Alpha2k
  • 2,212
  • 7
  • 38
  • 65
  • Maybe a related [article](http://stackoverflow.com/questions/16351273/how-to-disable-the-url-address-bar-using-javascript-or-jquery) – Drixson Oseña May 25 '15 at 08:39
  • I'm not sure that you can actually do that. For sure you can use the history API, listen for changes and if there is something forbidden then change the path immediately. – Krasimir May 25 '15 at 08:44
  • 1
    User should be allowed to navigate anywhere he wants from the navbar. Instead just redirect the user to `/news` despite any entered parameters – Pete TNT May 25 '15 at 08:44

2 Answers2

2

There are some known solutions :

  • ) Each time a user click a link - you save the page value to a cookie. Later , at the server- you check that interval ( value-1 ... value+1).

  • ) You can also save to a hidden field and check that value in the server.

So let's say a user is on page 3. ( the server serve that page - so a cookie/hidden value with value 3 is exists)

now he tries to go to page 10 :

you - in the server side - reads the cookie + requested Page number. if the interval is bigger than 1 - then you deny that request.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
1

Try adding an event listener:

window.addEventListener('popstate', function(event)
{
    var location = document.location;
    var state =  JSON.stringify(event.state);
});

To check the URL, The best thing would be to match it against a regex like:

if (url.match(/\?./)) {
  // do not allow access
}

You might need to extend this, depending on other URL's that you need to forbid access to.

Ioana Cucuruzan
  • 845
  • 1
  • 8
  • 21