How to dynamically change tab title when it is not selected?

时间:2015-09-01 22:40:19

标签: javascript dom dynamic title

I want to display dynamic information (score) in the window tab of a javascript games running in a browser (chrome) : my goal is to run several instances of the game in different tabs, running in parallel, and to be able to see the current scores in the tab titles. I tried :

document.title = score

... but it works only in the selected tab, the other one are not refreshed until selected (although the games are running well in background).

==> is there a way to force the update of the tab titles... even if not selected ?

1 个答案:

答案 0 :(得分:2)

我在http://stackoverflow.com上发现了几个相同的问题,但它们对我不起作用。

您可以在此处找到您的解决方案:http://www.raymondcamden.com/2010/10/19/Using-JavaScript-to-update-the-browser-window-title-when-the-user-is-away

所以,基本上这种代码会起作用:

var focused = true;
var baseTitle = "";
var chatsMissed = 0;

//I'm the fake function that represents some process. We randomly determine if a new chat happened
function fakeStuff() {
if(Math.random() > 0.5) {
if(!focused) {
chatsMissed++;
window.document.title = baseTitle + " ("+chatsMissed+")";
}
}
}

$(document).ready(function() {

//store the base title
baseTitle = window.document.title;

//When the window is focused...
$(window).focus(function() {
focused = true;
//  window.document.title = baseTitle;
//chrome bug: http://heyman.info/2010/oct/7/google-chrome-bug-when-setting-document-title/
setTimeout(function() {
document.title = baseTitle;
}, 100);

chatsMissed = 0;
});

//When the window is blurred...
$(window).blur(function() {
focused = false;
});

//setup a process
window.setInterval('fakeStuff()',2000);
})

不幸的是,JSfiddle不支持改变标题。但我测试了,它确实有效。