简体   繁体   中英

Differentiate between button click and javascript page reload

I'm trying to differentiate between page click and auto reload. Auto reload is done through javascript below.

var pageReload = {
Initialize: function () {
      window.setTimeout("location.reload(true);", 60000);
}
pageReload.Initialize();

I'm trying to set a hidden variable in the above code for which I'm trying to check the changed value in Page_PreRender to understand the difference between page click and auto reload.

var hdnReloadType = document.getElementById('<%=hdnReloadType.ClientID%>');
hdnReloadType.value = "1";

The javascript is loaded after PreRender and I'm sure how to proceed.

Any thoughts?

You could always use localStorage to leave a breadcrumb behind when your function reloads the page:

localStorage.setItem( 'page-reloaded', 'true' );

When the page loads, check for the breadcrumb:

var reloaded = localStorage.getItem('page-reloaded') || false;

And then cleanup afterwards:

localStorage.removeItem('page-reloaded');

Instead of just doing a reload() , you could add a "reloaded" parameter to the URL. If we use something like the replaceUrlParam() function from this answer , we can say:

var pageReload = {
  Initialize: function () {
    window.setTimeout(
      function() {
        var url = replaceUrlParam(window.location.href, 'reloaded', '1');
        window.location.href = url;
      },
      60000
    );
  }
}
pageReload.Initialize();

Now, when the page has been auto-reloaded (and only then), the query string will contain "reloaded=1".

Thank you for all the replies.

Because I'm using asp.net, I was able to capture the previous page click url from Request object and from there I'm determining if this was a page auto reload or button click. The query string reload option is great too but we didn't want to expose that to the user. This solution worked for my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM