MediaWiki:Common.js

De alcolois
Version datée du 6 mai 2025 à 13:58 par Marc (discussion | contributions) (Création de la page - code ES5 plutôt que ES6)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigation Aller à la recherche

Note : après avoir publié vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou appuyez sur Ctrl + F5 ou Ctrl + R (⌘ + R sur un Mac).
  • Google Chrome : appuyez sur Ctrl + Maj + R (⌘ + Shift + R sur un Mac).
  •  Edge : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl + F5.
/* Tout JavaScript présent ici sera exécuté par tous les utilisateurs à chaque chargement de page. */
/**
 * Opens in a new tab:
 * - all internal links to MediaWiki and Category namespaces
 * 
 * To add other namespaces, do the following:
 * 1. Add their numeric ID to the `targetedNS` array below.
 *    You can find these IDs using the browser console:
 *      console.table(mw.config.get('wgFormattedNamespaces'));
 * 
 * 2. Add their canonical name to the `namespaceNames.push(...)` line if needed.
 *    These are required to detect alias usages (e.g., [[:Category:Name]]).
 *    To get canonical names via the API:
 *      fetch('/w/api.php?action=query&meta=siteinfo&siprop=namespaces&format=json&uselang=en')
 *        .then(r => r.json())
 *        .then(data => console.table(data.query.namespaces));
 */

$(function () {
  var targetedNS = [8, 14]; // MediaWiki and Category

  // Get localized namespace names from MediaWiki configuration
  var namespaces = mw.config.get('wgFormattedNamespaces');
  var namespaceNames = [];

  targetedNS.forEach(function (ns) {
    var localized = namespaces[ns];
    if (localized) {
      namespaceNames.push(localized);
    }
  });

  // Manually add known canonical aliases (e.g., English names on a localized wiki)
  namespaceNames.push('Category', 'MediaWiki');

  // Build encoded URL prefixes for comparison
  var namespacePrefixes = namespaceNames.map(function (name) {
    return '/wiki/' + encodeURIComponent(name) + ':';
  });

  // Apply target="_blank" to internal links in targeted namespaces
  $('a[href]').each(function () {
    var href = $(this).attr('href');
    if (
      href &&
      href.indexOf('#') === -1 &&
      namespacePrefixes.some(function (prefix) {
        return href.indexOf(prefix) === 0;
      })
    ) {
      $(this).attr({
        target: '_blank',
        rel: 'noopener noreferrer'
      });
    }
  });
});