tl;dr - iOS 5 上的 Safari 缓存非常困难,它破坏了我的网站。
我正在努力解决 iOS 5 中 Safari 浏览器处理前后缓存(他们称之为“页面缓存”)的方式。描述方式here很好地解释了这种行为。
Quite simply, the Page Cache makes it so when you leave a page we “pause” it and when you come back we press “play.”
这导致我的整个网站出现问题。使用后退按钮时,大多数其他浏览器都会以加载状态显示页面。不是 iOS 5 上的 Safari,它会显示您上次离开时的页面。一个简单的例子是禁用提交按钮。如果我使用 Javascript 禁用提交按钮,然后提交表单,当您单击返回时,提交按钮仍将被禁用。这在其他浏览器中也是一个问题,包括桌面版 Safari,但通过将 onload 事件处理程序设置为空白函数可以解决这个问题。我相信这告诉浏览器使缓存无效,因为该函数中可能发生了一些重要的事情。此 hack 似乎不适用于 iOS 5 上的 Safari。
以下问题归结为最基本的问题。当您加载 test.html 时,您将看到文本“原始文本”。当您单击该链接时,该文本将更改为“已更改文本 - 转发到下一页”,然后 3 秒后您将转发到 test2.html。到目前为止,所有浏览器中一切都很好。在所有其他浏览器中,当您单击后退按钮时,您将看到的文本是“原始文本”,但在 iOS 5 的 Safari 上,您将看到“更改的文本 - 转发到下一页”。
关于如何处理这个问题有什么建议吗?
这是一个简单的例子
测试.html
<script>
function changeText() {
el = document.getElementById("text");
el.innerHTML = "Changed text - forwarding to next page";
setTimeout("forward()",3000);
}
function forward() {
document.location.href = "test2.html";
}
</script>
<div id="text">Original Text</div>
<a href="Javascript:changeText()">Click Here</a>
<script>
window.onunload = function(){};
</script>
test2.html
<div>Click back button</div>
这是使用表单帖子的第二个示例。这是我的应用程序如何工作的一个简单示例。当您导航回 formtest2.asp 时,您应该看到发布的表单值,并且 div 文本应该是原始的。
表单测试.asp
<form method="post" action="formtest2.asp">
Test: <input type="text" name="test"/>
<input type="submit" value="Submit"/>
</form>
formtest2.asp
<script>
function changeText() {
el = document.getElementById("text");
el.innerHTML = "Changed text - forwarding to next page";
setTimeout("forward()",3000);
}
function forward() {
document.location.href = "test2.html";
}
</script>
<%
Dim test
test = Request("test")
Response.Write("Test value: " & test & "<br />")
%>
<div id="text">Original Text</div>
<a href="Javascript:changeText()">Click Here</a>
<script>
window.onunload = function(){};
</script>
test2.html
<div>Click back button</div>
最佳答案
我也在寻找同一问题的答案。在 iOS 5 中返回不会执行任何 JavaScript,而只是将页面保留在您离开或重定向时的先前状态。
尝试在“Is there a cross-browser onload event when clicking the back button?”中发现的奇怪的“onunload”黑客仅适用于iOS 4,不适用于iOS 5,因为iOS 5不会按预期调用事件。 Nickolay 指出了 web-kit 上的新功能“pageshow”和“pagehide”,它们比 Giuseppe 的示例可靠得多。
- 您需要本文中的技巧:“Is there a cross-browser onload event when clicking the back button? ”才能在 iOS 4 中运行。
使用此脚本,该脚本使用新事件来安全地检查页面是否从缓存加载,并针对 iOS 5 强制重新加载(避免 URL 检查和本地存储,还包括 iPod):
<body onunload=""> ... <script type="text/javascript"> if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) { window.onpageshow = function(evt) { // If persisted then it is in the page cache, force a reload of the page. if (evt.persisted) { document.body.style.display = "none"; location.reload(); } }; } </script>
关于javascript - iOS 5 Safari 中导航后退/卸载事件未触发时出现页面缓存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988967/