メッセージをWebブラウザの外部に表示するAPIだ。

説明する前にTypeScriptを使うので、型定義ファイルを示しとく。

interface NotificationOptions {
	dir?: string;
	lang?: string;
	body?: string;
	tag?: string;
	icon?: string;
}

declare class Notification implements EventTarget {
	static permission: string;
	static requestPermission(callback: (permission: string) => void): void;
	
	onclick: (e: Event) => any;
	onshow: (e: Event) => any;
	onerror: (e: Event) => any;
	onclose: (e: Event) => any;
	
	dir: string;
	lang: string;
	body: string;
	tag: string;
	icon: string;
	
	close(): void;
	
	removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
	addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
	dispatchEvent(evt: Event);
	constructor(title: string, options?: NotificationOptions);
}

このAPI、IEでサポートしてないものだからだと思うが、型定義ファイルが用意されていない。(Visual Studio 2013にて)

また、Web Notifications APIに対応しているかチェックするのに

interface Window {
	Notification: Notification;
}

が必要だ。

Web Notifications APIに対応しているかどうかは、

if (window.Notification) {
	alert("通知に対応してる");
} else {
	alert("通知に対応してない");
}

で判定する。

メッセージを出す場合、ユーザから許可を得ているか、得ていないなら許可を得なければなりません。
許可を得ているかどうかは、Notification.requestPermissionプロパティが、"granted"でないと許可を得てないので許可を得るようにする。

if (Notification.permission !== "granted") {
	Notification.requestPermission((status) => {
		if (Notification.permission !== status) {
			Notification.permission = status;
		}
	});
}

こんな感じ。

そして、メッセージを出すには、

var hoge = new Notification("title", {
	body: "body",
	icon: "icon.png",
	tag: "tag",
})
hoge.onshow = (e) => {
	setTimeout((e) => { hoge.close(); }, 3000);
};

こんな感じ。自動的に消えないのでsetTimeoutで3秒後に閉じるようにしている。