如何建立應用程式徽章

徽章是用於向使用者傳達非緊急資訊。例如用於指出應用程式的狀態,或未讀取的項目數量。建立應用程式徽章的經典方式,是在網站小圖示中加入數字。 以新式瀏覽器而言,應用程式安裝完成後,作業系統工作列中有內建功能標記,可用來為圖示加入應用程式圖示。

navigator.setAppBadge() 方法會在與已安裝應用程式相關聯的圖示上設定標記。此方法會使用選用單一引數,做為徽章值使用的整數。將數字設為 0 即可清除應用程式標記。未提供引數會導致一般標記 (通常以彩色圓點顯示)。

顯示實際圖示的應用程式圖示,數字 3 為徽章值。

瀏覽器支援

  • 81
  • 81
  • x
  • 17

資料來源

經典風格

在網站小圖示中新增數字

如果你尚未安裝該應用程式,可以在網站小圖示中加入數字。有很多方法可以這麼做,例如將標記資訊以動態方式繪製到包含徽章資訊的畫布上,並以 Blob 網址顯示;或是以徽章資訊做為資料網址,製作 SVG 圖片。

網站小圖示顯示實際圖示,數字 5 為徽章值。

漸進式增強

下列程式碼片段使用自訂元素 <favicon-badge></favicon-badge>,讓開發人員將整數傳遞至 badge 屬性,以宣告方式為透過 src 屬性指定的網站小圖示設定標記。使用者安裝應用程式後,徽章會成為原生作業系統徽章。

import 'https://unpkg.com/favicon-badge@2.0.0/dist/FavIconBadge.js';

// DOM references.
const favicon = document.querySelector('favicon-badge');
const installButton = document.querySelector('button');

// Feature detection.
const supportsAppBadge = 'setAppBadge' in navigator;

let setAppBadge
;

// For the demo simply set the badge between [0, 9].
let i
= 0;
const getAppBadgeValue = () => {
 
if (i > 9) {
    i
= 0;
 
}
 
return i++;
};

// Set the badge on the favicon.
const setAppBadgeFavicon = (value) => {
  favicon
.badge = value;
};

// Set the native operating system badge.
const setAppBadgeNative = (value) => {
  navigator
.setAppBadge(value);
}

// If the app is installed and the Badging API is supported,
// set the badge on the native operating system. Else, fall
// back to the favicon.
if (
  matchMedia
('(display-mode: standalone)').matches &&
  supportsAppBadge
) {
  setAppBadge
= setAppBadgeNative;
} else {
  setAppBadge
= setAppBadgeFavicon;
}

// Set a new badge every second.
setInterval
(() => {
  setAppBadge
(getAppBadgeValue());
}, 1000);

// If installation is supported…
if ('BeforeInstallPromptEvent' in window) {
  let installEvent
= null;
 
const onInstall = () => {
   
// After installation, "upgrade" to the native operating system badge.
    installButton
.disabled = true;
    installEvent
= null;
   
if (supportsAppBadge) {
      favicon
.badge = false;
      setAppBadge
= setAppBadgeNative;
   
}
 
};

 
// …listen for the `beforeinstallprompt` event.
  window
.addEventListener('beforeinstallprompt', (event) => {
    event
.preventDefault();
    installEvent
= event;
    installButton
.disabled = false;
 
});

 
// Deal with installation.
  installButton
.addEventListener('click', async () => {
   
if (!installEvent) {
     
return;
   
}
    installEvent
.prompt();
   
const result = await installEvent.userChoice;
   
if (result.outcome === 'accepted') {
      onInstall
();
   
}
 
});

 
// Listen for the `appinstalled` in case the user installs the app manually.
  window
.addEventListener('appinstalled', (event) => {
    onInstall
();
 
});
}

延伸閱讀

示範

<!DOCTYPE html>
<html lang="en">
 
<head>
   
<meta charset="utf-8" />
   
<meta name="viewport" content="width=device-width, initial-scale=1" />
   
<link rel="manifest" href="manifest.json" />
   
<title>How to create an app badge</title>
   
<link rel="stylesheet" href="style.css" />
   
<!-- TODO: Devsite - Removed inline handlers -->
   
<!-- <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', async () => {
          const registration = await navigator.serviceWorker.register(
            'sw.js',
          );
          console.log(
            'Service worker registered for scope',
            registration.scope,
          );
        });
      }
    </script>
    <script src="script.js" type="module"></script> -->

 
</head>
 
<body>
   
<h1>How to create an app badge</h1>
   
<ol>
     
<li>
        Watch the favicon. You should see a counter that updates each second
        integrated into the favicon.
       
<img
         
src="../favicon.png"
         
style="width: 250px; height: auto"
         
width="528"
         
height="74"
         
alt="Favicon with counter."
       
/>
     
</li>
     
<li>
        Install the app by clicking the button below. After the installation,
        the button is disabled.
       
<p>
         
<button disabled type="button">Install</button>
       
</p>
     
</li>
     
<li>
        Watch the app icon in your operating system's task bar. You should see a
        counter that updates each second as an app badge.
       
<img
         
src="../app-badge.png"
         
style="width: 80px; height: auto"
         
width="282"
         
height="388"
         
alt="App badge with counter."
       
/>
     
</li>
   
</ol>
   
<favicon-badge src="../favicon.svg" textColor="#fff" badge="" />
 
</body>
</html>

        html
{
 
box-sizing: border-box;
 
font-family: system-ui, sans-serif;
 
color-scheme: dark light;
}

*, *:before, *:after {
 
box-sizing: inherit;
}

body
{
 
margin: 1rem;
}

img
{
 
height: auto;
 
max-width: 100%;
 
display: block;
}
       

       
import 'https://unpkg.com/favicon-badge@2.0.0/dist/FavIconBadge.js';

// The `