Chromeウェブアプリの多重起動を抑制するためのTips

Chromeウェブアプリは基本的に多重起動可能(複数のタブで開ける)。
そのため、ステートフルなウェブアプリで多重起動されてしまうと状態管理がめちゃくちゃになってしまう危険性がある。


ということでChromeウェブアプリの多重起動を抑制し、単一起動に限定させてみるテスト。
background_pageで以下のスクリプトを走らせとけばOK。

// ウェブアプリを開いているタブ
var theTab = undefined;

function changedHandler(tab) {
    // chrome.extension.getURL(path)で指定したリソースへのフルパスが取得できる
    // 引数pathはmanifest.jsonで定義したlocal_pathと一致させること
    if (tab.url === chrome.extension.getURL("index.html")) {
        if (theTab) {
            if (tab.id !== theTab.id) {
                // すでにアプリを開いているタブがある場合、そのタブにフォーカスする
                console.log("duplicated!");
                chrome.tabs.remove(tab.id);
                focus_to_the_tab();
            }
        } else {
            console.log("created");
            theTab = tab
        }
    } else {
        if (theTab && tab.id == theTab.id) {
            removeHandler(tab.id)
        }
    }
}

function removeHandler(tabId) {
    if (theTab && tabId === theTab.id) {
        console.log("closed");
        // アプリを開いているタブが閉じられた場合、タブ情報を初期化する
        theTab = undefined;
    }
}

function focus_to_the_tab() {
    if (theTab) {
        chrome.tabs.update(theTab.id, {selected:true});
    }
}

chrome.tabs.onCreated.addListener(function(tab) {
    changedHandler(tab)
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    changedHandler(tab);
});

chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
    removeHandler(tabId);
});