在浏览Firefox历史logging之后,JavaScript将无法运行

当我使用Firefox上的后退button访问先前访问过的页面时,该页面上的脚本将不会再次运行

是否有任何修复/解决方法让第二次查看页面时再次执行脚本?

请注意,我已经在Google Chrome浏览器和Internet Explorer上testing了相同的页面,并且按照预期工作。


以下是我用来testing问题的文件和步骤:

(导航到0.html,点击进入1.html,返回button)

0.html

<html><body> <script> window.onload = function() { alert('window.onload alert'); }; alert('inline alert'); </script> <a href="1.html">Click Me!</a> </body></html> 

1.HTML

 <html><body> <p>Go BACK!</p> </body></html> 

设置一个在window.onunload上被调用的空函数:

 window.onunload = function(){}; 

例如

 <html><body> <script type="text/javascript"> window.onload = function() { alert('window.onload alert'); }; window.onunload = function(){}; alert('inline alert'); </script> <a href="1.html">Click Me!</a> </body></html> 

资料来源: http : //www.firefoxanswer.com/firefox/672-firefoxanswer.html (存档版本)

当我使用Firefox上的后退button访问先前访问过的页面时,该页面上的脚本将不会再次运行。

这是正确的,这是一件好事。

当你点击Firefox中的链接(以及Safari和Opera)时,它不会立即破坏你的页面进入下一个页面。 它保持页面完好,只是隐藏它的视图。 如果您点击后退button,则会将旧页面重新放入视图中,而无需再次加载文档; 这要快得多,导致用户的后退/前进页面转换更平滑。

这个特性被称为bfcache 。

您在用户上次加载和使用期间添加到页面的任何内容仍将保留在那里。 您附加到页面元素的任何事件处理程序仍将附加。 您设置的任何超时/间隔将仍然有效。 所以你很less有任何理由需要知道你被隐藏和重新显示。 再次调用onload或内联脚本代码是错误的,因为您在该函数中执行的任何绑定和内容生成都将在相同内容上执行第二次操作,并可能导致灾难性后果。 (例如,内联脚本中的document.write会完全破坏页面。)

写入window.onunload的原因是,实现bfcache的浏览器已经决定 – 为了与真正需要知道什么时候被丢弃的页面兼容 – 任何声明有兴趣知道何时发生onunload页面将会导致bfcache被禁用。 那个页面在你回到它时会被加载,而不是从bfcache中获取。

所以如果你设置window.onunload= function() {}; ,你实际上在做什么是故意打破bfcache。 这将导致您的网页导航速度缓慢,不应该使用,除非作为最后的手段。

如果您确实需要知道用户何时离开或返回到您的页面,而不会弄乱bfcache,则可以捕获onpageshowonpagehide事件:

 window.onload=window.onpageshow= function() { alert('Hello!'); }; 

您可以检查pageshow事件的persisted属性。 它在初始页面加载时设置为false。 当从caching中加载页面时,它被设置为true。

 window.onpageshow = function(event) { if (event.persisted) { alert("From bfcache"); } }; 

出于某种原因,jQuery在事件中没有这个属性。 你可以从原始事件中find它。

 $(window).bind("pageshow", function(event) { if (event.originalEvent.persisted) { alert("From bfcache"); } }); 

在不执行任何操作的“onunload”事件中连线:

 <html><body> <script type="text/javascript"> window.onload = function() { alert('window.onload alert'); }; window.onunload = function(){}; alert('inline alert'); </script> <a href="1.html">Click Me!</a> </body></html> 

据我所知Firefox不会在后面onLoad事件。

它应该触发onFocus而不是基于这个链接在这里 。

当用户使用浏览器历史logging导航到页面时,导致页面执行JavaScript的一种简单方法是OnPopState事件。 我们用这个来暂停和重播我们主页上的video( https://fynydd.com )。

 window.onpopstate = function() { // Do stuff here... }; 

对于一些像ajax操作可以使用url更改监听器的情况

 $(window).on('hashchange', function() { .... });