manager.js 3.36 KB
var isSupportPWA = (function () {
    var isSupportServiceWorker = "serviceWorker" in window.navigator;
    var isHttpsProtocol = window.location.protocol === "https:";
    var isLocalHost = ~["localhost", "127.0.0.1"].indexOf(window.location.hostname);

    return isSupportServiceWorker && (isHttpsProtocol || isLocalHost);
}());

if (isSupportPWA) {
    // 注册失败后, 注销已存在的serviceworker
    navigator.serviceWorker.getRegistrations().then(function (registrations) {
        if (!registrations.length) return renderTable([], "Service Worker尚未注册, 请注册后刷新该页面!");

        registrations.forEach(function (registration) {
            if (registration.scope.match(/.*\/mobilemode\/mobile\/$/g)) {
                document.querySelector("#btn").addEventListener("click", function (e) {
                    e.preventDefault();
                    sendMessage({ command: "report" }).then(function (res) {
                        renderTable(res.data);
                    }).catch(function (e) {
                        renderTable([], e);
                    });
                });
                document.querySelector("#btn").click();
            }
        });
    });
}

function sendMessage(message) {
    return new Promise(function (resolve, reject) {
        var messageChannel = new MessageChannel();

        messageChannel.port1.onmessage = function (event) {
            if (event.data.error) {
                reject(event.data.error);
            } else {
                resolve(event.data);
            }
        };

        var controller = navigator.serviceWorker.controller;

        if (!controller) {
            return reject("Service worker未处于已激活状态, 请尝试刷新页面!")
        }

        controller.postMessage(message, [messageChannel.port2]);
    });
}

function renderTable(data, errormsg) {
    var report = document.querySelector("#report");
    var tbody = report.querySelector("tbody");
    var tmpl = "<tr><td title='${title}'>${name}</td><td width='72px'>${size}</td><td width='125px'>${date}</td></tr>";
    var tmpls = "";
    var _render = function (html) {
        tbody.innerHTML = html;
        report.style.visibility = "visible";
    };

    if (errormsg) return _render("<tr><td class='no-record error' colspan='3'>" + errormsg + "</td></tr>");
    if (!data.length) return _render("<tr><td class='no-record' colspan='3'>暂无记录!</td></tr>");

    data = data.filter(function(d) {
        return !!d.size;
    }).map(function (d) {
        var date = d.lastModified, size;
        var _toDouble = function(str) {
            str = String(str);

            if(str.length === 1) {
                str = "0" + str;
            }
            return str;
        };

        date = [date.getFullYear(), _toDouble(date.getMonth() + 1), _toDouble(date.getDate())].join("-") + " "
            + [_toDouble(date.getHours()), _toDouble(date.getMinutes())].join(":");
        size = Math.round((d.size / 1024) * 10) / 10;
    
        return {
            name: d.pathname.substring(d.pathname.lastIndexOf("/") + 1),
            title: d.url,
            size: ~String(size).indexOf(".") ? size : size + ".0",
            date: date || "无"
        };
    });

    tmpls = data.reduce(function (prev, o) {
        return prev + tmpl.replace(/\${(.*?)}/g, function (a, p) {
            return o[p];
        });
    }, "");

    _render(tmpls);
}