|
| 1 | +// Open external (different-origin) links in a new tab; keep internal doc links in the same tab. |
| 2 | +(function () { |
| 3 | + function isSkippableScheme(href) { |
| 4 | + var h = (href || '').trim().toLowerCase(); |
| 5 | + return ( |
| 6 | + !h || |
| 7 | + h.indexOf('#') === 0 || |
| 8 | + h.indexOf('javascript:') === 0 || |
| 9 | + h.indexOf('mailto:') === 0 || |
| 10 | + h.indexOf('tel:') === 0 |
| 11 | + ); |
| 12 | + } |
| 13 | + |
| 14 | + function enhanceExternalLinks() { |
| 15 | + var root = document.querySelector('.md-content') || document.body; |
| 16 | + root.querySelectorAll('a[href]').forEach(function (a) { |
| 17 | + var href = a.getAttribute('href'); |
| 18 | + if (isSkippableScheme(href)) return; |
| 19 | + |
| 20 | + try { |
| 21 | + var abs = new URL(href, window.location.href); |
| 22 | + if (abs.origin === window.location.origin) return; |
| 23 | + } catch (e) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + a.setAttribute('target', '_blank'); |
| 28 | + var rel = (a.getAttribute('rel') || '').trim(); |
| 29 | + var parts = rel ? rel.split(/\s+/) : []; |
| 30 | + if (parts.indexOf('noopener') === -1) parts.push('noopener'); |
| 31 | + if (parts.indexOf('noreferrer') === -1) parts.push('noreferrer'); |
| 32 | + a.setAttribute('rel', parts.join(' ').trim()); |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + var debounceTimer; |
| 37 | + function scheduleEnhance() { |
| 38 | + clearTimeout(debounceTimer); |
| 39 | + debounceTimer = setTimeout(enhanceExternalLinks, 50); |
| 40 | + } |
| 41 | + |
| 42 | + if (document.readyState === 'loading') { |
| 43 | + document.addEventListener('DOMContentLoaded', enhanceExternalLinks); |
| 44 | + } else { |
| 45 | + enhanceExternalLinks(); |
| 46 | + } |
| 47 | + |
| 48 | + if (typeof MutationObserver !== 'undefined' && document.body) { |
| 49 | + var mo = new MutationObserver(scheduleEnhance); |
| 50 | + mo.observe(document.body, { childList: true, subtree: true }); |
| 51 | + } |
| 52 | +})(); |
0 commit comments