Jump to content

MediaWiki:Gadget-OpenExternal.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// Open all external links on a new window
mw.loader.using(['mediawiki.util']).then(function () {
    function openExternalLinks() {
        // Define internal actions that should not open in a new tab
        const internalLinkActions = [
            'edit', 
            'history', 
            'delete', 
            'submit', // For forms like Special:UserLogin, Special:Upload
            'watch', 
            'unwatch', 
            'protect', 
            'unprotect', 
            'markpatrolled',
            'purge', // action=purge
            'render' // action=render
        ];
        const currentHostname = window.location.hostname;
        // General external and interwiki links
        document.querySelectorAll('a.external, a.extiw').forEach(function (link) {
            try {
                // Ensure link.href is an absolute URL before parsing; if link.href is relative, new URL() needs a base
                const linkUrl = new URL(link.href); 
                const linkAction = linkUrl.searchParams.get('action');
                // Check if it's an internal link AND has one of the specified actions
                if (linkUrl.hostname === currentHostname && linkAction && internalLinkActions.includes(linkAction)) {
                    // It's an internal action link, don't open in a new tab
                    return; 
                }
                // For all other links with class 'external'
                link.setAttribute('target', '_blank');
                link.setAttribute('rel', 'noopener noreferrer');
            } catch (e) {
                // Fallback for non-HTTP/HTTPS links or if URL parsing fails
                console.warn('JS/Common.js: Could not parse URL for link, applying default external link behavior for "a.external":', link.href, e);
                link.setAttribute('target', '_blank');
                link.setAttribute('rel', 'noopener noreferrer');
            }
        });

        // Social media links within templates
        document.querySelectorAll('div.external-social a, div.ntldstats a').forEach(function (link) {
            link.setAttribute('target', '_blank');
            link.setAttribute('rel', 'noopener noreferrer');
        });
    }
    mw.hook('wikipage.content').add(openExternalLinks);
});