參考 Gmail 實驗室功能,利用 PHP GD 库在瀏覽器分頁圖示上直接繪製未讀郵件計數,讓使用者無需切換分頁即可掌握新訊息。
<?php
// favicon.php
$im = imagecreatefrompng("favicon.png"); // 支援 jpg/bmp 同理
// 取得要繪製的文字(預設 'V')
$text = isset($_GET['char']) && $_GET['char'] !== '' ? $_GET['char'] : 'V';
// 分配顏色
$bg = imagecolorallocate($im, 255, 255, 255); // 白底
$fg = imagecolorallocate($im, 0, 0, 0); // 黑字
// 繪製單一字元(字體大小 2,座標 5,1)
imagechar($im, 2, 5, 1, $text, $fg);
// 輸出 PNG
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
<!-- 預設 favicon -->
<link rel="icon" href="favicon.png" id="favicon">
<script>
function updateFavicon(count) {
const link = document.getElementById('favicon');
if (count > 0) {
link.href = 'favicon.php?char=' + encodeURIComponent(count > 99 ? '99+' : count);
} else {
link.href = 'favicon.png';
}
}
// 範例:每 30 秒輪詢未讀數
setInterval(() => fetch('/api/unread').then(r => r.json()).then(d => updateFavicon(d.count)), 30000);
</script>
imagettftext() 配合 TTF 字型可繪製完整數字data:image/png;base64,... 避免額外 HTTP 請求| 瀏覽器 | 支援情況 |
|---|---|
| Chrome 60+ | 完整支援動態更新 |
| Firefox 55+ | 完整支援 |
| Safari 12+ | 支援,需透過 rel="mask-icon" |
| Edge 79+ | 完整支援 |