跳转到内容

MediaWiki:Common.js:修订间差异

FC留言 | 贡献
 
FC留言 | 贡献
标签替换
 
第1行: 第1行:
/* 这里的任何JavaScript将为所有用户在每次页面加载时加载。 */
/* 这里的任何JavaScript将为所有用户在每次页面加载时加载。 */
/* Decode percent-encoded UTF-8 in wiki link hrefs so copied links
  show 中文 instead of %E9%A6%96... in WeChat/QQ/text editors.
  Browser auto-re-encodes when the link is clicked, so navigation is unaffected. */
(function () {
    function decodeHref(href) {
        try {
            var m = href.match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);
            if (!m) return href;
            var path = decodeURIComponent(m[1]);
            var query = '';
            if (m[2]) {
                query = '?' + m[2].slice(1).split('&').map(function (p) {
                    var eq = p.indexOf('=');
                    if (eq === -1) { try { return decodeURIComponent(p); } catch (e) { return p; } }
                    var k = p.slice(0, eq), v = p.slice(eq + 1);
                    try { k = decodeURIComponent(k); } catch (e) {}
                    try { v = decodeURIComponent(v); } catch (e) {}
                    return k + '=' + v;
                }).join('&');
            }
            var hash = m[3] || '';
            if (hash.length > 1) {
                try { hash = '#' + decodeURIComponent(hash.slice(1)); } catch (e) {}
            }
            return path + query + hash;
        } catch (e) { return href; }
    }
    function isInternal(a) {
        var raw = a.getAttribute('href');
        if (!raw) return false;
        if (raw.charAt(0) === '/' && raw.charAt(1) !== '/') return true;
        try { return new URL(a.href, window.location.href).host === window.location.host; }
        catch (e) { return false; }
    }
    function decodeAll(root) {
        var nodes = (root || document).querySelectorAll('a[href*="%"]');
        for (var i = 0; i < nodes.length; i++) {
            var a = nodes[i];
            if (!isInternal(a)) continue;
            var orig = a.getAttribute('href');
            var dec = decodeHref(orig);
            if (dec !== orig) a.setAttribute('href', dec);
        }
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { decodeAll(); });
    } else { decodeAll(); }
    if (window.mw && mw.hook) {
        mw.hook('wikipage.content').add(function ($content) {
            decodeAll($content[0] || $content);
        });
    }
})();