Files
sproutblog/public/js/cwd-comments.js
2026-04-15 13:20:51 +08:00

79 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function () {
/**
* cwd-widget≤0.1.11)里 getLikeStatus 用 post_slug = 完整页面 URLpostUrl
* 而点赞写入 likePage 用的是 postSlug后端排行榜按 slug 汇总,导致前台一直显示 0。
* getPagePv 已写成 postUrl || postSlug点赞查询未对齐。这里把 GET /api/like 的
* post_slug 从绝对地址改回与评论区一致的 slug。
*/
function patchCwdLikeGetQuery(apiBaseNorm, postSlug) {
if (window.__cwdLikeStatusQueryPatched) return;
window.__cwdLikeStatusQueryPatched = true;
var base = apiBaseNorm;
var orig = window.fetch;
window.fetch = function (input, init) {
var url =
typeof input === "string"
? input
: input && typeof input.url === "string"
? input.url
: "";
var method = "GET";
if (init && init.method) method = String(init.method).toUpperCase();
else if (typeof Request !== "undefined" && input instanceof Request) {
method = String(input.method || "GET").toUpperCase();
}
if (
url &&
url.indexOf(base) === 0 &&
url.indexOf("/api/like?") !== -1 &&
method === "GET"
) {
try {
var u = new URL(url);
var ps = u.searchParams.get("post_slug") || "";
if (ps.indexOf("://") !== -1) {
u.searchParams.set("post_slug", postSlug);
if (typeof input === "string") {
input = u.toString();
} else if (typeof Request !== "undefined" && input instanceof Request) {
input = new Request(u.toString(), input);
}
}
} catch (e) {
/* ignore */
}
}
return orig.call(this, input, init);
};
}
function mount() {
var el = document.getElementById("comments");
if (!el || typeof CWDComments === "undefined") return;
var ds = el.dataset;
var apiBaseUrl = ds.apiBase;
var postSlug = ds.postSlug;
if (!apiBaseUrl || !postSlug) return;
patchCwdLikeGetQuery(apiBaseUrl.replace(/\/$/, ""), postSlug);
var opts = {
el: "#comments",
apiBaseUrl: apiBaseUrl,
postSlug: postSlug,
lang: ds.lang || "zh-CN"
};
if (ds.siteId) opts.siteId = ds.siteId;
new CWDComments(opts).mount();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", mount);
} else {
mount();
}
})();