It is very common to use the web title to prompt users for new messages, such as Weibo and some email addresses, which are very common. How to implement a function?
The idea is: access the background through ajax. If there is a new message, replace the title of the web page with a prompt message and switch back and forth with the space. Example: [You have new news] and [ ] toggle. The prompt content is dynamic, so the number of spaces in the replacement text is also calculated. Use full-width spaces here. However, if there are half-width characters such as 'number' in the prompt message, there will be problems. The spaces at the full-width are much wider than the width of the half-width 1. In this way, it will not be very comfortable to flash; the solution is to replace the characters in the full-width with spaces in the full-width, and the spaces in the half-width.
But document.title=' ';No matter how many half-width spaces are, the browser only displays one. If used, it outputs as is; only var t=document.getElementsByTagName('title')[0] can be used. Get the title dom object and modify it by t.innerHTML=' '.
But will it go so smoothly, of course not. Our cute ie will always come out to make trouble at this time. In the ie browser, the innerHTML of the title is read-only (not only the title, but the innerHTML attributes of COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TR are read-only). If a forced assignment is made, an "Unknown runtime error" will occur. At present, I have not found a very good solution, so I can only add try{}catch(e){} to deal with it specially
Share the source code:
The code copy is as follows:
<script type="text/javascript" language="javascript">
var flashTitlePlayer = {
start: function (msg) {
this.title = document.title;
if (!this.action) {
try {
this.element = document.getElementsByTagName('title')[0];
this.element.innerHTML = this.title;
this.action = function (ttl) {
this.element.innerHTML = ttl;
};
} catch (e) {
this.action = function (ttl) {
document.title = ttl;
}
delete this.element;
}
this.toggleTitle = function () {
this.action('【' + this.messages[this.index = this.index == 0 ? 1 : 0] + ']Welcome to simple modern magic");
};
}
this.messages = [msg];
var n = msg.length;
var s = '';
if (this.element) {
var num = msg.match(//w/g);
if (num != null) {
var n2 = num.length;
n -= n2;
while (n2 > 0) {
s += " ";
n2--;
}
}
}
while (n > 0) {
s += ' ';
n--;
};
this.messages.push(s);
this.index = 0;
this.timer = setInterval(function () {
flashTitlePlayer.toggleTitle();
}, 1000);
},
stop: function () {
if (this.timer) {
clearInterval(this.timer);
this.action(this.title);
delete this.timer;
delete this.messages;
}
}
};
function flashTitle(msg) {
flashTitlePlayer.start(msg);
}
function stopFlash() {
flashTitlePlayer.stop();
}
</script>
Firefox, no problem under Chrome, no problem when ie is prompted that there is one or no half-width characters in the message.