Alert, confirm, and prompt not working after using History API on Safari, iOS

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-29 03:32:10

问题


After calling history.pushState in Safari on iOS, it's no longer possible to use alert(), confirm() or prompt(), when using the browser back button to change back.

Is this an iOS bug? Are there any known workarounds?

Simple example to reproduce this behavior:

<html>
  <body>
    <ul>
      <li>Step 1: <button onclick="alert(Math.random())">Confirm Alert is working</button></li>
      <li>Step 2: <button onclick="history.pushState(null, null, '/debug/'+Math.random());">Change History</button></li>
      <li>Step 3: use your browser back button, to go back</li>
      <li>Step 4: <button onclick="alert(Math.random())">Alert is not working anymore</button></li>
    </ul>
  </body>
</html>

You can try it online here: goo.gl/faFW6o.


回答1:


This is because of the back-forward cache in Safari.

You can use the following code to force a reload when the back-button is pressed.

window.onpageshow = function(e) { // e -> event
    if (e.persisted) {
        window.location.reload(); 
    }
};

Additionally, if you are using jQuery ...

$(window).bind("pageshow", function(e) { // e -> event
    if (e.originalEvent.persisted) {
        window.location.reload();
    }
});



回答2:


one workaround would be instead the property onload on the button, create a function adding the listeners then call it on window.onpopstate and window.onload..



来源:https://stackoverflow.com/questions/38083702/alert-confirm-and-prompt-not-working-after-using-history-api-on-safari-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!