javascript如何检查浏览器是否获得焦点 [英] javascript how check if browser got focus

查看:83
本文介绍了javascript如何检查浏览器是否获得焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于Meanjs的工作聊天,我想向其中添加一个新功能,我可以在其他可用聊天中看到该功能:

I have a working chat based on Meanjs and I would like to add a new feature to it that I see on other chats available:

功能:1.收到消息后,窗口的标题开始在显示的标题和新消息"之类的通知消息之间切换2.当浏览器或标签页获得焦点时,停止正在进行的活动并重置为静态页面标题

Feature: 1. when a message is received, the title of the window starts to switch between what it was, and a notification message like "new message" 2. when the browser or tab receives the focus, to stop the ongoing activity and reset back to the static page title

第一个只是有一个计时器并在一定间隔内更改页面标题,但我不知道如何获得浏览器获得焦点或失去焦点的事件.

The first one is simply to have a timer and change the page title during an interval, but I don't know how to get the event of the browser getting or losing the focus.

我可以简单地向浏览器询问如何检测焦点",但是我解释了我的目的,希望了解该特定用例中的最佳做法并了解更多信息.

I could simply ask "how detect focus" for the browser, but I explained my purpose to hopefully know the best practice in this particular use-case and learn more.

将欢迎并欣赏课程.

推荐答案

简单来说,您可以使用本机javascript事件处理程序检查窗口是否处于焦点状态.我们将使用window.onblur检查窗口是否未聚焦,并使用window.onfocus检查窗口是否聚焦.

Simply, you can check whether window is on focus or not by using native javascript event handler. we will use window.onblur to check if window isn't on focus and use window.onfocus to check if window is on focus.

    window.onblur = function(){
      // do some event handler here...in your case, to show new message alert on the title if the user receive new message.
       newMessageChecker();
    }
    window.onfocus = function(){
       // invoke another function to bring back your default title and destroy the Interval you have created.
       destroyMessageChecker();
    }
    function newMessageChecker(){
      // check if the user have new message. you may use setInterval method
      window.messageChecker = setInterval(function(){
            // if true, do some stuff like this
               document.title = "New Message("+ messageCount +") : " + yourDefaultTitleValue;
      }, 3000);
    }
    function destroyMessageChecker(){
      // change your title to default value
      document.title = yourDefaultTitleValue;
      clearInterval(window.messageChecker);
    }

有关窗口事件的更多信息,请查看此链接窗口事件属性.如果您更喜欢使用jQuery,请检查此页面

for more information about window event, please take a look at this link Window Event Attributes. if you prefer to use jQuery please check this page Using jQuery to bind "focus" and "blur" functions for "window"

这篇关于javascript如何检查浏览器是否获得焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆