2015-05-02 25 views
0

我有一個基於Meanjs工作聊天,我想一個新的功能添加到它,我看到其他可用的聊天記錄:的JavaScript如何檢查,如果瀏覽器得到了集中

特點:1. 當消息收到時,窗口標題開始在它之間的切換和「新消息」之類的通知消息之間切換。2.當瀏覽器或標籤收到焦點時,停止正在進行的活動並重置回靜態頁面標題

第一個只是有一個計時器,並在一段時間內更改頁面標題,但我不知道如何讓瀏覽器事件得到或失去焦點。

我可以簡單地問:「怎麼檢測爲關注焦點」的瀏覽器,但我解釋了我的目的是希望知道在這個特殊的用例的最佳實踐,瞭解更多信息。

將歡迎和欣賞課程。

+0

看看這個SO關於標籤焦點的問題:http://stackoverflow.com/questions/7389328/detect-if-browser-tab-has-focus –

回答

1

簡單地說,你可以通過使用原生javascript事件處理程序來檢查窗口是否處於焦點狀態。我們將使用window.onblur來檢查窗口是否在焦點上並使用window.onfocus來檢查窗口是否在焦點上。

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); 
    } 

約窗口事件的更多信息,請看一看這個鏈接Window Event Attributes。如果你喜歡使用jQuery,請查看本頁Using jQuery to bind 「focus」 and 「blur」 functions for 「window」

+0

非常感謝你很多,對不起,我沒有足夠的聲望投票回答 –

+0

沒問題Mr.Dain。玩的開心! –

相關問題