manager.js
3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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);
}