Jump to content

MediaWiki:Common.js

From Shark's Hypothetical Weather

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.
/* Any JavaScript here will be loaded for all users on every page load. */

mw.hook('wikipage.content').add(function() {
    if (mw.config.get('wgCanonicalSpecialPageName') === 'Search') {
        const searchResults = document.querySelectorAll('.mw-search-result-heading a');

        searchResults.forEach(function(link) {
            // Fetch the page linked
            fetch(link.href)
                .then(response => response.text())
                .then(html => {
                    const doc = new DOMParser().parseFromString(html, 'text/html');
                    const shortDescDiv = doc.querySelector('div.shortdescription');
                    if (shortDescDiv && shortDescDiv.textContent.trim() !== '') {
                        const desc = shortDescDiv.textContent.trim();
                        const resultContainer = link.closest('.mw-search-result');
                        if (resultContainer) {
                            const descElement = document.createElement('div');
                            descElement.className = 'search-shortdesc';
                            descElement.style.fontSize = '85%';
                            descElement.style.color = '#666';
                            descElement.style.marginTop = '0.2em';
                            descElement.textContent = desc;
                            resultContainer.appendChild(descElement);
                        }
                    }
                });
        });
    }
});

$(function() {
    var shortdesc = $('div.shortdescription').text().trim();

    if (shortdesc.length > 0) {
        // SHORTDESC exists: replace the old meta description
        $('meta[name="description"]').remove();

        $('<meta>', {
            name: 'description',
            content: shortdesc
        }).appendTo('head');
    } else {
        // No SHORTDESC: delete any description tag
        $('meta[name="description"]').remove();
    }
});