How can I stop the browser back button using JavaScript?

前端 未结 30 3334
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:07

I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.

I have tried the following script, but it stops my timer.

30条回答
  •  青春惊慌失措
    2020-11-22 01:12

    I came across this, needing a solution which worked correctly and "nicely" on a variety of browsers, including Mobile Safari (iOS9 at time of posting). None of the solutions were quite right. I offer the following (tested on IE11, FireFox, Chrome & Safari):

    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event)
    {
      history.pushState(null, document.title, location.href);
    });
    

    Note the following:

    • history.forward() (my old solution) does not work on Mobile Safari --- it seems to do nothing (i.e. the user can still go back). history.pushState() does work on all of them.
    • the 3rd argument to history.pushState() is a url. Solutions which pass a string like 'no-back-button' or 'pagename' seem to work OK, until you then try a Refresh/Reload on the page, at which point a "Page not found" error is generated when the browser tries to locate a page with that as its Url. (The browser is also likely to include that string in the address bar when on the page, which is ugly.) location.href should be used for the Url.
    • the 2nd argument to history.pushState() is a title. Looking around the web most places say it is "not used", and all the solutions here pass null for that. However, in Mobile Safari at least, that puts the page's Url into the history dropdown the user can access. But when it adds an entry for a page visit normally, it puts in its title, which is preferable. So passing document.title for that results in the same behaviour.

提交回复
热议问题