跳转到内容

MediaWiki:Common.js

来自失传媒体中文维基
HW留言 | 贡献2026年2月19日 (四) 12:12的版本

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
// 修复编辑取消后的死循环问题
// 修复取消编辑后跳转到 index.php 的问题,自动转为 /wiki/ 短链接
(function() {
    // 仅在 Minerva 皮肤下生效
    if (mw.config.get('skin') !== 'minerva') return;

    // 提取 URL 中的标题并转为短链接的核心函数
    function fixEditCancelUrl() {
        const currentUrl = window.location.href;
        const titleRegex = /index\.php\?title=([^&]+)/; // 匹配 index.php?title=xxx 格式
        const match = currentUrl.match(titleRegex);

        // 1. 如果匹配到 index.php?title=xxx 格式
        if (match && match[1]) {
            const pageTitle = decodeURIComponent(match[1]); // 解码标题(比如 %E9%A6%96%E9%A1%B5 → 首页)
            const shortUrl = `/wiki/${encodeURIComponent(pageTitle)}`; // 构造 /wiki/标题 格式

            // 2. 用 replaceState 重写 URL(无刷新跳转,避免编辑器死循环)
            window.history.replaceState(null, document.title, shortUrl);
            
            // 3. 强制刷新页面内容(确保是浏览模式,而非编辑模式)
            if (!document.querySelector('.ve-init-mw-desktopArticleTarget')) {
                mw.loader.using('mediawiki.api').then(() => {
                    new mw.Api().get({
                        action: 'parse',
                        page: pageTitle,
                        prop: 'text',
                        format: 'json'
                    }).done((data) => {
                        const content = document.querySelector('main#content, #content');
                        if (content && data.parse) {
                            content.innerHTML = data.parse.text['*'];
                        }
                    });
                });
            }
        }
    }

    // 监听时机:页面加载完成 + URL 变化时都执行
    // 1. 页面首次加载时检查
    document.addEventListener('DOMContentLoaded', fixEditCancelUrl);

    // 2. 监听浏览器历史变化(取消编辑会触发 popstate)
    window.addEventListener('popstate', fixEditCancelUrl);

    // 3. 额外监听 1 秒(防止异步跳转漏检)
    setTimeout(fixEditCancelUrl, 1000);
})();