Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...