@@ -15,6 +15,22 @@ const config = {
1515<div id =" tcomment" ></div >
1616<script is:inline src =" /assets/js/twikoo.all.min.js" ></script >
1717<script is:inline define:vars ={ { config }} >
18+ // 获取当前页面路径的函数
19+ function getCurrentPath() {
20+ const pathname = window.location.pathname;
21+ // 移除末尾的斜杠(如果存在)
22+ return pathname.endsWith('/') && pathname.length > 1 ? pathname.slice(0, -1) : pathname;
23+ }
24+
25+ // 动态创建配置对象的函数
26+ function createTwikooConfig() {
27+ return {
28+ ...config,
29+ path: getCurrentPath(),
30+ el: '#tcomment'
31+ };
32+ }
33+
1834 // 初始化 Twikoo 的函数
1935 function initTwikooWithRetry() {
2036 let retryCount = 0;
@@ -28,8 +44,10 @@ const config = {
2844 commentEl.innerHTML = '';
2945 }
3046
31- // 初始化 Twikoo
32- twikoo.init(config);
47+ // 使用动态配置初始化 Twikoo
48+ const dynamicConfig = createTwikooConfig();
49+ console.log('Twikoo 初始化配置:', dynamicConfig);
50+ twikoo.init(dynamicConfig);
3351 } else if (retryCount < maxRetries) {
3452 retryCount++;
3553 console.log(`Twikoo 加载重试 ${retryCount}/${maxRetries}...`);
@@ -46,23 +64,47 @@ const config = {
4664 document.addEventListener('DOMContentLoaded', initTwikooWithRetry);
4765
4866 // 监听 Swup 页面切换事件,在内容替换后重新初始化 Twikoo
49- if (window.swup) {
50- window.swup.hooks.on('content:replace', function() {
51- // 延迟执行以确保 DOM 已完全更新
52- setTimeout(function() {
53- // 检查当前页面是否为文章页面(通过检查评论容器是否存在)
54- if (document.getElementById('tcomment')) {
55- console.log('Swup 页面切换后重新初始化 Twikoo');
56- initTwikooWithRetry();
67+ function setupSwupHooks() {
68+ if (window.swup && window.swup.hooks) {
69+ // 在页面内容替换后重新初始化
70+ window.swup.hooks.on('content:replace', function() {
71+ // 延迟执行以确保 DOM 已完全更新
72+ setTimeout(function() {
73+ const commentEl = document.getElementById('tcomment');
74+ if (commentEl) {
75+ console.log('Swup 页面切换后重新初始化 Twikoo,当前路径:', getCurrentPath());
76+ initTwikooWithRetry();
77+ }
78+ }, 200);
79+ });
80+
81+ // 在页面访问开始时清理旧的评论数据
82+ window.swup.hooks.on('visit:start', function() {
83+ const commentEl = document.getElementById('tcomment');
84+ if (commentEl) {
85+ commentEl.innerHTML = '';
86+ console.log('页面切换开始,清理评论容器');
5787 }
58- }, 200);
59- });
88+ });
89+ }
90+ }
91+
92+ // 设置 Swup 钩子
93+ if (window.swup) {
94+ setupSwupHooks();
95+ } else {
96+ document.addEventListener('swup:enable', setupSwupHooks);
6097 }
6198
6299 // 监听自定义事件,在页面完全加载后重新初始化 Twikoo
63- document.addEventListener('mizuki:page:loaded', function() {
64- console.log('Mizuki 页面加载完成事件触发,重新初始化 Twikoo');
65- if (document.getElementById('tcomment')) {
100+ document.addEventListener('mizuki:page:loaded', function(event) {
101+ const eventDetail = event.detail || {};
102+ console.log('Mizuki 页面加载完成事件触发,路径:', eventDetail.path, '时间戳:', eventDetail.timestamp);
103+
104+ const commentEl = document.getElementById('tcomment');
105+ if (commentEl) {
106+ // 确保在自定义事件触发时也使用最新的路径
107+ console.log('通过自定义事件重新初始化 Twikoo,当前路径:', getCurrentPath());
66108 initTwikooWithRetry();
67109 }
68110 });
0 commit comments