Files
svfs/svfs-plugins-root/com.svfs.demo/blobs/70/70bf75a25ed8bf3404a390f37b036ef6179ca45093ca4dbd4c5685758eeaee6f
T

80 lines
2.9 KiB
Plaintext
Raw Normal View History

/* 演示插件的前端逻辑:全部能力都走宿主注入的 window.svfs(Promise)。 */
"use strict";
var $ = function (id) { return document.getElementById(id); };
var PLUGIN_VERSION = "2.0.0";
function randomColor() {
var letters = "0123456789abcdef", out = "#";
for (var i = 0; i < 6; i++) out += letters[Math.floor(Math.random() * 16)];
return out;
}
async function main() {
if (!window.svfsReady) {
$("missing").hidden = false;
$("version").textContent = "插件 " + PLUGIN_VERSION + "(未连接宿主)";
return;
}
var svfs = await window.svfsReady;
var info = await svfs.host.info();
$("version").textContent = "插件 " + PLUGIN_VERSION + " · 桥 API v" + info.apiVersion;
$("host-info").innerHTML = "";
[["插件 id", info.pluginId], ["宿主", info.appName + " " + info.appVersion],
["平台", info.platform], ["来源", info.source || "-"]]
.forEach(function (row) {
var dt = document.createElement("dt"); dt.textContent = row[0];
var dd = document.createElement("dd"); dd.textContent = row[1];
$("host-info").append(dt, dd);
});
// storage:按插件隔离的键值存储,换一台机器/重装插件也不会串到别的插件
var count = 0;
try {
count = parseInt(await svfs.storage.get("visits"), 10) || 0;
count += 1;
await svfs.storage.set("visits", count);
} catch (e) { /* 没拿到 storage 权限时静默降级 */ }
$("count").textContent = String(count);
$("reset").onclick = async function () {
await svfs.storage.set("visits", 0);
$("count").textContent = "0";
svfs.ui.notify("计数已清零");
};
$("add10").onclick = async function () {
count += 10;
await svfs.storage.set("visits", count);
$("count").textContent = String(count);
};
$("notify").onclick = function () {
svfs.ui.notify("来自 " + info.pluginId + " 的通知(" + PLUGIN_VERSION + ")");
};
$("paint").onclick = function () {
svfs.ui.setTitle("SVFS Client · 演示插件 " + randomColor());
};
// net:宿主代发 HTTP 请求(不经过浏览器的 CORS)。相对 path 拼在
// 客户端配置的服务器地址(base_url)后;也可以给 {url: "https://…"}。
$("ping").onclick = async function () {
if (!svfs.net) {
$("net-out").textContent = "这个宿主没有 net 能力(需要客户端支持桥 API v2)";
return;
}
$("net-out").textContent = "请求中…";
try {
var res = await svfs.net.request({ method: "GET", path: "/api/ping" });
$("net-out").textContent = "HTTP " + res.status + "\n"
+ (res.bodyText || "(空响应)").slice(0, 300);
} catch (e) {
$("net-out").textContent = "请求失败: " + e.message
+ "\n(先在「插件管理 → 服务器」里配置地址,服务端需提供 /api/ping)";
}
};
$("changelog").textContent = "v2:新增主题色切换与变更记录";
}
main();