Is there a way to detect if the user has pressed the refresh button using jquery or javascript?

前端 未结 5 2032
[愿得一人]
[愿得一人] 2021-01-22 12:48

I want to know if jquery or javascript can detect if the user has pressed the refresh button of their browser? If so can I see an example?

相关标签:
5条回答
  • 2021-01-22 12:57

    I'm not sure you can do that, but what you could do instead as a hacky workaround is maybe render the referring page URL from the server into a hidden input or something, and on page load, check to see if the value of the hidden div is the same as the current URL. If it is, it must be a postback or a refresh.

    0 讨论(0)
  • 2021-01-22 12:59

    there is 1 way to detect it.

    check to see if F5 was pressed. as to detect if the actual refresh was clicked, that i'm not sure if its possible, but you can check against the key code

    JS Code .keypress()

    0 讨论(0)
  • 2021-01-22 13:06

    window.onunload event will be fired before the page is going to be refreshed.

    window.onunload = function(){
        alert("unload event detected!");
    }
    
    0 讨论(0)
  • 2021-01-22 13:09

    There is no way to detect if the user pressed refresh before the page refreshes, but you can use cookies to determine if the page refreshed once it loads the second time.

    For example, each page could store the location.href in a cookie, and if the last cookie equals the same location.href of the current page, then the user most likely refreshed the page.

    0 讨论(0)
  • 2021-01-22 13:15

    Well if you are looking to detect if user press F5 or ctrl+ f5 then you can use following code :)

    $("body").keydown(function (e)
    {
       if (e.which == 116 || e.which == 17) {
         inFormOrLink = true;
       }
    });
    
    0 讨论(0)
提交回复
热议问题