Javascript 移动 Safari 后退按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11979156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mobile Safari back button
提问by Sal
The issue I've found is very similar to this question, except that Safari on desktops seems to have resolved the issue. Essentially, the issue is this: when a client is browsing on mobile safari and the page executes a javascript function on pagea.html, then navigate to pageb.html, then press the back button to go back to pagea.html, the javascript function won't run when the client pressed the back button to come back to pagea.html. It will skip the javascript call.
我发现的问题与这个问题非常相似,只是桌面上的 Safari 似乎已经解决了这个问题。本质上,问题是这样的:当客户端在移动 safari 上浏览并且页面在 pagea.html 上执行 javascript 函数时,然后导航到 pageb.html,然后按后退按钮返回 pagea.html,javascript 函数当客户端按下后退按钮返回 pagea.html 时不会运行。它将跳过 javascript 调用。
I've tried the solutions mentioned in the link above, but nothing seems to work for mobile Safari. Has anyone else encountered this bug? How did you handle it?
我已经尝试了上面链接中提到的解决方案,但似乎对移动 Safari 没有任何作用。有没有其他人遇到过这个错误?你是怎么处理的呢?
回答by Mika Tuupola
This is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.
这是由back-forward cache引起的。当用户导航离开时,它应该保存页面的完整状态。当用户使用后退按钮向后导航时,可以非常快速地从缓存中加载页面。这与仅缓存 HTML 代码的普通缓存不同。
When page is loaded for bfcache onload
event wont be triggered. Instead you can check the persisted
property of the onpageshow
event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.
当页面加载时 bfcacheonload
事件不会被触发。相反,您可以检查事件的persisted
属性onpageshow
。它在初始页面加载时设置为 false。当页面从 bfcache 加载时,它被设置为 true。
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
出于某种原因,jQuery 在事件中没有这个属性。你可以从原始事件中找到它。
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From back / forward cache.");
}
});
Quick solution to these problem is to reload the page when back button is pressed. This however nullifies any positive effect back / forward cache would give.
这些问题的快速解决方案是在按下后退按钮时重新加载页面。然而,这抵消了向后/向前缓存带来的任何积极影响。
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
As a sidenote, you can see lot of pages offering using empty onunload
handler as solution. This has not worked since iOS5.
作为旁注,您可以看到许多页面提供使用空onunload
处理程序作为解决方案。自 iOS5 以来,这不起作用。
$(window).bind("unload", function() { });