日本語

“React: Show an Unread Count in the Tab Title and Favicon”

​​React​Canvas API,custom hook,Playwright,TypeScript,useEffect

When there are 3 unread items, the browser tab shows (3) 猫のメモ, and I draw a pink circle with "3" at the top right of the favicon. The idea is that even with other tabs open, you can tell from the tab row that something new has arrived.

The title is changed by passing a string that includes the count to React 19's <title>. For the favicon, I draw the original image on a canvas, draw the count over it, make a PNG, and put it in the href of a <link rel="icon">.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and served them from a test server written in Node.js. To capture the tab display, I ran Chromium as a non-headless window on a virtual screen provided by Xvfb. I did not test Firefox, Safari, mobile browsers, or server-side rendering. I also did not test what happens when the tab is put in the background. (Pages opened with Playwright kept document.visibilityState as visible even when I brought another tab to the front.)

Above, a 2x enlargement of the tab area; below, the whole browser window. Pressing the button labeled `新着を1件受け取る` (Receive 1 new item; the label is in Japanese) three times changes the tab title from `猫のメモ` to `(1) 猫のメモ`, `(2) 猫のメモ`, and `(3) 猫のメモ`, and a pink circle with a number appears at the top right of the favicon. Pressing the button labeled `すべて既読にする` (Mark all as read; the label is in Japanese) restores the title and favicon.
The tab title and the favicon count change each time a button is pressed

The GIF was recorded from a window displaying the page at 1.5x zoom. The upper strip is the tab area cropped from the same screen and enlarged 2x. The click counter at the top right, the cursor, and the circle showing where I clicked were added for the recording. The count on the page is shown in pink only at the moment it changes.

Adding the count to the start of the title

The title gets the count at the start only when there are unread items, as in (3) 猫のメモ. Counts of 100 or more are shown as 99+.

tsx
export function formatCount(count: number) {
  return count > 99 ? '99+' : String(count);
}

export function UnreadTitle({ count, title }: { count: number; title: string }) {
  // Keep the content of <title> as a single string
  const text = count > 0 ? `(${formatCount(count)}) ${title}` : title;
  return <title>{text}</title>;
}

In React 19, a <title> written inside a component is moved by React into <head>. As the official <title> reference says, the content of <title> must be a single string. If you mix in a value with JSX {}, as in <title>({count}) 猫のメモ</title>, the content becomes an array. That is why I build one string with a template literal and pass that. I covered this pitfall in the earlier article "How to Write title and meta Inside Components in React 19."

These are the document.title values when I changed the count in the test environment:

Unread count document.title
0 猫のメモ
1 (1) 猫のメモ
10 (10) 猫のメモ
99 (99) 猫のメモ
100 (99+) 猫のメモ

The test index.html already had <title>猫のメモ</title> written in it. When I added React's <title>, there were two <title> elements in <head>, but document.title showed the one with the count. However, the official reference notes that the browser's behavior with multiple <title> elements is not specified. I examined what happens when there are two in more detail in the earlier article. When I unmounted the component, document.title went back to 猫のメモ from index.html.

Drawing the count on the favicon

For the favicon, I draw the original image (a 32×32px PNG) on a canvas, then overlay a pink rounded rectangle and white digits at the top right. When the count has two or more digits, I make the font smaller and stretch the rectangle horizontally.

ts
import { formatCount } from './UnreadTitle';

const SIZE = 32;

export function loadImage(src: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous'; // Load cross-origin images with CORS
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`画像を読み込めません: ${src}`));
    img.src = src;
  });
}

export function drawBadgeIcon(base: HTMLImageElement, count: number): string {
  const canvas = document.createElement('canvas');
  canvas.width = SIZE;
  canvas.height = SIZE;
  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('canvas に描けません');

  ctx.drawImage(base, 0, 0, SIZE, SIZE);

  const label = formatCount(count);
  ctx.font = `bold ${label.length === 1 ? 20 : 15}px sans-serif`;
  const width = Math.max(20, ctx.measureText(label).width + 6);
  const height = 20;
  const x = SIZE - width;
  const y = 0;

  // Draw a rounded rectangle at the top right, sized to fit the digits
  ctx.fillStyle = '#d85878';
  ctx.beginPath();
  ctx.roundRect(x, y, width, height, height / 2);
  ctx.fill();

  ctx.fillStyle = '#ffffff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(label, x + width / 2, y + height / 2 + 1);

  return canvas.toDataURL('image/png');
}

The rounded rectangle is drawn with roundRect(). Its height is 20px and its corner radius is half of that, so one digit gives a circle and two or more digits give a wider rounded shape. Finally, toDataURL() turns the drawing into a string in the form data:image/png;base64,…. That string can be put directly into href.

When I enlarged the favicons generated in the test environment by 4x and lined them up, they looked like this:

Six icons in a row, each a light blue rounded square with a white cat face. The first, with 0 items, is unchanged. The ones for 1 and 9 items have a pink circle with a white number at the top right. The ones for 10 and 99 items have a slightly wider rounded shape. The one for 100 items has a wider rounded shape reading "99+".
Favicons generated for each count (32×32px, enlarged 4x)

The image above is enlarged 4x. The favicon in the tab is displayed much smaller than this. In the lower strip of the GIF above, the screen at 1.5x zoom was captured at its actual size, and the upper strip is that image enlarged 2x. On this screen, a single digit such as "3" was readable. I did not check how it looks at 1x zoom, or with two or more digits or 99+ in the tab.

A hook that rewrites the link href

The generated image is displayed by rewriting the href of the <link rel="icon"> that already exists in index.html.

ts
import { useEffect } from 'react';
import { drawBadgeIcon, loadImage } from './drawBadgeIcon';

function getIconLink() {
  return document.querySelector<HTMLLinkElement>('link[rel="icon"]');
}

export function useFaviconBadge(count: number, baseHref: string) {
  useEffect(() => {
    const link = getIconLink();
    if (!link) return;
    if (count <= 0) {
      link.href = baseHref;
      return;
    }
    let ignore = false;
    loadImage(baseHref)
      .then((img) => {
        if (!ignore) link.href = drawBadgeIcon(img, count);
      })
      .catch((error) => {
        console.warn('ファビコンにバッジを描けません', error);
      });
    return () => {
      ignore = true; // Keep an outdated count's drawing from overwriting later ones
    };
  }, [count, baseHref]);

  // When unmounted, restore the original icon
  useEffect(() => {
    return () => {
      const link = getIconLink();
      if (link) link.href = baseHref;
    };
  }, [baseHref]);
}

I rewrite the one existing <link rel="icon"> instead of adding a new one, for a reason. According to the MDN description of the rel attribute, when there are several <link rel="icon"> elements, the browser looks at the media, type, and sizes attributes and picks the best match. The one you add is not guaranteed to be used. In my tests, there was always exactly one <link rel="icon">, even when the count changed. Note that this hook rewrites only the first one it finds. Based on the MDN description, on a page that lists several icons of different sizes with sizes, the browser could pick one this hook did not rewrite, so the count would not appear. I did not test this case.

Loading an image is asynchronous, so the count can change while an image is loading. To handle that, I set ignore to true in the cleanup function, following the official example of fetching data with an effect. If an image for an old count finishes loading later, it is not drawn and href is not rewritten.

In my test, I pressed the button three times in a row. href was rewritten only once, and the image was the same as when I had pressed the button one at a time to reach 3. The results of the first and second loads were not used.

The second useEffect restores the original icon when the component is unmounted. When I unmounted the component with a count of 2, href went back to /favicon.png. When I ran a development build with StrictMode enabled, the image for 3 items and the href after marking everything as read were the same as in the production build.

Using it in a component that holds the unread count

In the component that uses this, pass the unread count to both UnreadTitle and useFaviconBadge. In my test, I increased the count with buttons and reset it to 0.

tsx
import { useState } from 'react';
import { UnreadTitle } from './UnreadTitle';
import { useFaviconBadge } from './useFaviconBadge';

export function Inbox({ iconHref = '/favicon.png' }: { iconHref?: string }) {
  const [unread, setUnread] = useState(0);
  useFaviconBadge(unread, iconHref);

  return (
    <main>
      <UnreadTitle count={unread} title="猫のメモ" />
      <h1>猫のメモ</h1>
      <p className="unread">
        未読 <output data-testid="unread">{unread}</output> 件
      </p>
      <button onClick={() => setUnread((n) => n + 1)}>新着を1件受け取る</button>
      <button onClick={() => setUnread(0)}>すべて既読にする</button>
    </main>
  );
}

In the <head> of index.html, put the base <title> and <link rel="icon"> that the code above uses.

html
<title>猫のメモ</title>
<link rel="icon" type="image/png" href="/favicon.png">

When the original icon is on a different origin

If the original icon is served from another origin, such as a CDN, the count may not be drawable. According to the MDN explanation of using cross-origin images in a canvas, if you draw an image from another origin that was loaded without CORS permission, the canvas becomes "tainted," and calling toDataURL() throws an error.

In my test, I served the app from 127.0.0.1:8100 and served only the icon from 127.0.0.1:8101. Since the port numbers differ, these are different origins.

How the image was loaded Response from the icon server Result
No crossOrigin Access-Control-Allow-Origin: * present toDataURL() throws SecurityError
crossOrigin = 'anonymous' No CORS header Image loading failed, and the icon stayed as the original
crossOrigin = 'anonymous' Access-Control-Allow-Origin: * present The count was drawn

As the first row shows, even if the server returns a CORS header, the canvas is tainted unless the crossOrigin attribute is set on the <img> side. This is why loadImage in the article sets crossOrigin = 'anonymous'.

In the second row, the browser console showed an error saying the request was blocked by CORS, and the Promise from loadImage failed. useFaviconBadge only logs a warning, and href stayed as the original icon. In this case, the count in the title still appeared as (1) 猫のメモ.

Point

The simplest approach is to host the original icon on the same origin as the app. If you host it on a different origin, configure the server to return Access-Control-Allow-Origin, and load the image with crossOrigin = 'anonymous'.

​Posted by 86