javascript 焦点后如何刷新页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11313434/
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
How to refresh page after focus?
提问by jrn
I would like to refresh a page after it got back into the focus. For the refreshing part I thought I might just use:
我想在页面重新成为焦点后刷新页面。对于令人耳目一新的部分,我想我可以只使用:
location.reload();
The tricky part is how do I determine when to refresh?
First the window has to loose the focus (which could be determined through .blur()I assume).
Only after the window which lost focus gets back into focus should trigger the refresh of itself. Can I use .focus()on location? Or do I have to use something else here?
棘手的部分是我如何确定何时刷新?
首先,窗口必须松开焦点(我假设可以通过.blur()确定)。
只有在失去焦点的窗口重新获得焦点后,才会触发自身的刷新。我可以在位置上使用.focus()吗?还是我必须在这里使用其他东西?
How can I combine these two cases?
我怎样才能将这两种情况结合起来?
What would your approach be?
你的方法是什么?
回答by Beat Richartz
Try this:
试试这个:
var blurred = false;
window.onblur = function() { blurred = true; };
window.onfocus = function() { blurred && (location.reload()); };
This only reloads the page if it has been hidden
如果页面被隐藏,这只会重新加载页面
I don't recommend binding to the window focus in jQuery, the Page will reload on pretty much every user action.
我不建议在 jQuery 中绑定到窗口焦点,页面几乎会在每个用户操作时重新加载。
Update
更新
This heavily relies on the browser implementation of window.onfocus and window.onblur. Webkit may not support the onblur event (in my chromium it didn't) where firefox calls a blur if the page is hidden.
这在很大程度上依赖于 window.onfocus 和 window.onblur 的浏览器实现。Webkit 可能不支持 onblur 事件(在我的 Chrome 中它不支持),如果页面被隐藏,firefox 会调用模糊。
回答by Eamonn
In my development environment I add this snippet of JS to a page - whenever the page becomes active after becoming inactive it reloads, so for example if you type in your text editor then click back onto your browser the page will reload once without an infinite loop. It also works when chaining active tab or active window within the same browser session.
在我的开发环境中,我将此 JS 片段添加到页面中 - 每当页面在变为非活动状态后变为活动状态时,它会重新加载,例如,如果您在文本编辑器中输入内容,然后单击回浏览器,页面将重新加载一次而不会无限循环. 它也适用于在同一浏览器会话中链接活动选项卡或活动窗口。
window.onblur= function() {window.onfocus= function () {location.reload(true)}};
As stated above this does depend on browser implementation but works fine in chrome.
如上所述,这确实取决于浏览器的实现,但在 chrome 中工作正常。
回答by Kamran Muazzam
@Eamonn 's approach works good for chrome as mentioned by him.
@Eamonn 的方法适用于他提到的 chrome。
For Firefox:
对于火狐:
window.disableResetPrompt;
window.onblur= function() {window.onfocus= function () {location.reload(true)}};