13
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

最後のBrowserが閉じる場合に…と言う処理を無理矢理やる方法

Last updated at Posted at 2014-10-24

Chromeのみで確認。

「Browserを閉じる場合のみ」と言うイベントは存在しません。

onunloadかonbeforeunloadを使うとそれっぽくなるような気がするのですが、リロード時や、場合によっては起動時にもonunload/onbeforeunloadが走ります。

onunload.png

厳密に「Browserを閉じる場合にXXしたい」と言うの方法は、ありません。(Chrome Ver. 38.0.2125.104で確認)

それでも最後のBrowserを閉じる時にXXしたい!がやりたい場合

onunload/onbeforeunloadで仕掛けを作り、onloadでその条件ならば実行となります。

具体的にはこんな感じで

onunload
  時間をlocalstorageに記録する
onload
  最後のBrowserの場合
    現在の時刻から60秒経過していたら、XXする。

リロード時は60秒かからないので、処理は行われない。

app.ts
/// <reference path="./service/window_service.ts" />

module Hoge {
    "use strict";

    export var appName = "hoge";
    var uid = "";
    angular.module(
            appName + ".run",
        []
    )
        .run((windowService: WindowService, $window:ng.IWindowService) => {
            // 強制ログアウトを一旦やめることになる。
            $($window).on("load", () => {
                uid = windowService.load(uid);
            });

            $($window).on("beforeunload", () => {
                windowService.unload(uid);
            });
        });

window_service.ts
module Hoge {
    "use strict";

    export class WindowService {

        constructor(public $window:ng.IWindowService) {
        }

        /**
         * 画面表示時
         * @param uid 現在の画面ID
         * @returns 新しい画面ID
         */
        load(uid:string):string {
            var windowUIDs:string[] = [];
            if (uid === "") {
                // 新規Openの場合はlocalStrageにuidを保存する
                windowUIDs = this.getItemWindowUIDs();
                while (true) {
                    uid = Math.random() + "";
                    if (windowUIDs.indexOf(uid) === -1) {
                        // ユニークなuidが出来たらwhileを抜ける(基本的には1回でwhileループを抜ける)
                        break;
                    }
                    // ここに来ることはほぼない
                    console.log("create duplicate random uid = " + uid);
                }
                windowUIDs.push(uid);
                this.setItemWindowUIDs(windowUIDs);
            }
            if (1 < windowUIDs.length) {
                // すでに開いている場合はlogouttimeは無効
                this.$window.localStorage.removeItem("LogoutTime");
            }
            var logoutTime = this.$window.localStorage.getItem("LogoutTime");
            if (logoutTime !== null) {
                var nowTime = Date.now();
                var diffTime = (nowTime - parseInt(logoutTime, 10)) / 1000;
                this.$window.localStorage.removeItem("LogoutTime");
                if (60 < diffTime) {
                    // 1分超えてたらログアウト画面に飛ばす
                    this.$window.localStorage.setItem("Logout", true.toString());
                    // TODO ここで処理をする
                }
            }
            return uid;
        }

        /**
         * unload時に時間をlocalStorageに保存する
         * @param uid 登録するメッセージデータ
         */
        unload(uid:string):void {
            var windowUIDs = this.getItemWindowUIDs();
            var index = windowUIDs.indexOf(uid);
            if (index !== -1) {
                // 基本的にはindexはあるハズ
                windowUIDs.splice(index, 1);
            }
            this.setItemWindowUIDs(windowUIDs);
            if (windowUIDs !== null && windowUIDs.length === 0) {
                //ここでログアウト処理をする
                var isLogout = this.getLogout();
                if (isLogout === null) {
                    // ログアウト処理中で無ければlogoutTimeを格納
                    var logoutTime = this.getLogoutTime();
                    if (logoutTime === null) {
                        this.setLogoutTime(Date.now());
                    }
                } else {
                    this.removeLogout();
                }
            } else {
                // 最後のWindowで無ければlogoutTimeは消す
                this.removeLogoutTime();
            }
        }

        getItemWindowUIDs():string[] {
            var values = this.$window.localStorage.getItem("WindowUIDs");
            if (values != null) {
                return JSON.parse(values);
            } else {
                return [];
            }
        }

        setItemWindowUIDs(windowUIDs:string[]):void {
            this.$window.localStorage.setItem("WindowUIDs", JSON.stringify(windowUIDs));
        }

        getLogout():string {
            return this.$window.localStorage.getItem("Logout");
        }

        getLogoutTime():string {
            return this.$window.localStorage.getItem("LogoutTime");
        }

        setLogoutTime(logoutTime:number):void {
            this.$window.localStorage.setItem("LogoutTime", logoutTime.toString());
        }

        removeLogout():void {
            this.$window.localStorage.removeItem("Logout");
        }

        removeLogoutTime():void {
            this.$window.localStorage.removeItem("LogoutTime");
        }
    }
}

言うまでもないですが、「本当に無理矢理やってみた」と言う感じで、あまりスマートな方法ではありません。

もっと簡単な方法があったら教えてください。

13
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?