javascript - Prevent page reloading continuously -


i'm using window.history.pushstate({) inside function. works fine expected. below example.

$('#go_btn').click(function(){    if ($('.green')) {         var newurl = "cutomurl.html";         if(newurl!=window.location){              window.history.pushstate({path:newurl},'',newurl);         }         return false;    } }); 

and i've got below code able refresh page when newurl being triggered $('#go_btn') button.

$(window).on('popstate', function(){      location.reload(true);  }); 

on desktop version don't seem have issues. when try load page on ipad continuously keeps on reloading page on over again. how stop continuous reloading , make page refresh when window.history.pushstate({path:newurl},'',newurl); being triggered?

note calling history.pushstate() or history.replacestate() won't trigger popstate event. popstate event triggered doing browser action such clicking on button (or calling history.back() in javascript). , event triggered when user navigates between 2 history entries same document.

browsers tend handle popstate event differently on page load. chrome (prior v34) , safari emit popstate event on page load, firefox doesn't.
according mozzila developer network
https://developer.mozilla.org/en-us/docs/web/api/windoweventhandlers/onpopstate

safari emit popstate event on page load. means

  1. your page loads
  2. popstate event occurs
  3. location.reload() executes
  4. it repeating

update: please, read documentation manipulation browser history. https://developer.mozilla.org/en-us/docs/web/guide/api/dom/manipulating_the_browser_history

it looks misunderstand functionality.

you have #go_btn button. when click it, want page to:

1. reload

use location.reload()

if (newurl != window.location) {     // window.history.pushstate({path:newurl},'',newurl);     location.reload(true); } 

2. navigate new url

use location.href. open new page in current window.

if (newurl != window.location) {     // window.history.pushstate({path:newurl},'',newurl);     location.href = newurl; } 

3. change url in browser history , address bar without doing anything.

use window.history.pushstate() or window.history.replacestate(). doesn't open new page or reloads it. used when not going navigate want user new url (for convenient browsing, history or favorites).

if (newurl!=window.location) {     window.history.pushstate({path:newurl},'',newurl); } 

in of there 3 cases don't need popstate event. used other purposes.

which 1 need? it's task.
anyway, using 2 of them not illogical , useless. reason of pushing history state if going refresh page? navigate then.


Comments