Outils pour utilisateurs

Outils du site


greasemonkey

Ceci est une ancienne révision du document !


GreaseMonkey

Cette page d'adresse aux développeurs. Débutants s’abstenir.

C'est quoi ?

GreaseMonkey est une extension Firefox qui permet de modifier à la volée n'importe quelle page web, à chaque fois qu'elle est chargée. Par exemple, pour changer la couleur de fond de votre site favorit, ou supprimer une partie de la page qui vous gêne à chaque visite, ou encore pour modifier tous les liens d'une page.

Comment ça marche ?

Installez d'abord l'extension Firefox, puis ajoutez les scripts de votre choix, ou créez-en vous-même. Ces scripts (écrits en javascript) manipulent la page web au moment où elle est chargée. Les scripts sont définis pour s'activer sélectivement sur certains site et certaines pages.

:!: ATTENTION: Ne téléchargez pas n'importe quel script. Les scripts peuvent faire n'importe quoi dans les pages. Utilisez votre cerveau.

Écrire soi-même un script

C'est le but de cette page.

Généralement, quand on veut écrire un script GreaseMonkey, c'est pour supprimer ou modifier quelque chose dans une page. Voici quelques fonctions utilitaires pour simplifier les choses.

monscript.js
// ==UserScript==
// @name        Essai
// @namespace   sebsauvage.net
// @include     http://sebsauvage.net/links/*
// ==/UserScript==
 
 
(function () {
    // Removes all occurences of elements whose XPath is provided from the document.
    //
    // Example: Remove all tables which use the CSS class 'toto':
    //          removeElement("//table[@class='toto']");
    function removeElement(ElementXpath)
    {
        var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
        for (i=0; i<alltags.snapshotLength; i++)
        {
            element = alltags.snapshotItem(i);
            element.parentNode.removeChild(element);  // Remove this element from its parent.
        }
    }  
 
    // Removes an attribute from all occurences of elements whose XPath is provided.
    // (All occurences of this elements are processed.)
    //
    // Example: Remove the bgcolor of all <table>:
    //          removeAttributeOfElement('bgcolor',"//table[@bgcolor]")
    //          Remove the fixed with of all tables or cells::
    //          removeAttributeOfElement('width',"//table[@width]|//td[@width]")
    function removeAttributeOfElement(attributeName,ElementXpath)
    {
        var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
        for (i=0; i<alltags.snapshotLength; i++)
            alltags.snapshotItem(i).removeAttribute(attributeName);    
    }
 
    // Set an attribute from all occurences of elements to a specified value.
    // The previous value of this attribute is discarded.
    // (All occurences of this elements are processed.)
    //
    // Example: Set with to 80 columns on all texteareas:
    //          setAttributeOfElement('cols',80,"//textarea")
    function setAttributeOfElement(attributeName,attributeValue,ElementXpath)
    {
        var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
        for (i=0; i<alltags.snapshotLength; i++)
            alltags.snapshotItem(i).setAttribute(attributeName, attributeValue)
    }    
 
    // Inject your own CSS in the page.
    // Example: Do not underline link:
    //          injectCSS("a{text-decoration: none;}")
    function injectCSS(cssdata)
    {
        head = document.getElementsByTagName("head")[0];
        style = document.createElement("style");
        style.setAttribute("type", 'text/css');
        style.innerHTML = cssdata;
        head.appendChild(style);
    }
 
 
    // Converts an image to text.
    // Attributes, links and javascript actions are preserved.
    //
    // Examples: imageToText("//img[@src='/forum/images/editer-bleu.png']","[Editer]")
    //           imageToText("//img[@src='/images/g.gif' or @src='../images/g.gif']","[Gras] "),
    function imageToText(ElementXpath,text)
    {
        var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
        for (i=0; i<alltags.snapshotLength; i++)
        {
            tag = alltags.snapshotItem(i)
            lien = document.createTextNode(text)
            tag.parentNode.replaceChild(lien, tag);
        }    
    }
 
    try
    {
        /*
 
        //======================================================================   
        // Colonne centrale:
 
        // Suppression des éléments en haut de la colonne de la page principale des forums
        // (liste et description des forums, rappel des us et coutumes, etc.)
        // ( http://www.commentcamarche.net/forum/ )        
        //removeElement("//div/p/b[starts-with(.,'tous les utilisateurs du site se doivent de respecter les autres')]/../../*[position()>=6 and position()<=9]");
 
        // Dans la page d'accueil des forum, suppression de la table qui donne la liste des
        // forum et le nombre de discussion.
        removeElement("//th[text()='Nombre de discussions']/ancestor::table[1]");
 
        // Suppression du rappel de la liste des forum (situé entre la discussion et la zone de saisie de réponse)
        removeElement("//td/div/h2[text()='Forums']/following::table[1]");
        removeElement("//td/div/h2[text()='Forums']");
 
        // Agrandissement des zones de saisie:
        //   - message dans forum
        //   - devise dans le profil.
        //   - signature dans le profil.
        //   - édition du descriptif logiciel dans section téléchargement
        //   - édition article dans la base de connaissances.
        setAttributeOfElement('rows','40',"//textarea[@name='message' or @name='Pdevise' or @name='description']");
        setAttributeOfElement('cols','120',"//textarea[@name='message' or @name='Pdevise' or @name='description' or @name='signature']");       
 
        // Dans la liste des discussion, on met en gras (et fond jaune clair) les discussions qui n'ont reçu aucune réponse.
        setAttributeOfElement('style','font-weight:bold; background-color:#FFFFE8',"//tr/td[position()=last() and text()='0']/../descendant::*");
 
        // Dans la liste des discussion, on met en gris clair les discussions supprimées.
        setAttributeOfElement('style','color:#aaa;background-color:#f9f9f9;',"//tr/td[position()=last() and text()='X']/../descendant::*");
 
        // Forcer la taille du texte dans la liste des discussions.
        setAttributeOfElement('style','font-size:8pt;','//tr[@class=\"fb\"]/td')
        setAttributeOfElement('style','font-size:8pt;','//tr[@class=\"fa\"]/td')
 
        // Supprimer la date dans la liste des discussions
        removeElement("//span[@class='Datered' or @class='Dategris' or @class='Date']/following-sibling::br");
        removeElement("//span[@class='Datered' or @class='Dategris' or @class='Date']");
 
        // On convertit certaines images en liens texte.
        var imgs = new Array(  new Array("//img[@src='/images/star0b.png' or @src='/images/star0a.png']","[Pertinence]"),
                               new Array("//img[@src='/forum/images/editer-bleu.png']","[Editer]"),
                               new Array("//img[@src='/forum/images/mp-bleu.png']","[MP]"),
                               new Array("//img[@src='/forum/images/autres-messages-bleu.png']","[Autres messages]"),
                               new Array("//img[@src='/forum/images/forum-bleu.png']","[Retour forum]"),
                               new Array("//img[@src='/forum/images/moderer-bleu.png']","[Modérer]"),
                               new Array("//img[@src='/images/g.gif' or @src='../images/g.gif']","[Gras] "),
                               new Array("//img[@src='/images/i.gif' or @src='../images/i.gif']","[Italique] "),
                               new Array("//img[@src='/images/s.gif' or @src='../images/s.gif']","[Souligné] "),
                               new Array("//img[@src='/images/code.gif' or @src='../images/code.gif']","[Code] "),
                               new Array("//img[@src='/images/image.gif' or @src='../images/image.png']","[Image] "),
                               new Array("//img[@src='/images/ccmlink.png']","[CCM] "),
                               new Array("//img[@src='/images/link.png']","[Lien] "),
                               new Array("//img[@src='/images/carregold.png' or @src='/images/carre.gif']","")
                               )
        for (index in imgs) { imageToText(imgs[index][0],imgs[index][1]); }
 
 
        // Dans la liste des discussions, on met les modos en orange.
//         var modos = new Array ("_Agnes","asevere","blux","BmV","brupala","Castor","chat_teigne","choubaka","dje-dje","dohm",
//                                "Eaulive","Jeff","jipicy","kalamit","mr_poussy","Sebastien","sebsauvage","Serge","sirhill",
//                                "teebo","teutates","Thom@s","Yoan","Obeet");
//         for (index in modos)
//             setAttributeOfElement('style','color:#FFA200',"//a[text()='"+modos[index]+"']");            
 
 
        //======================================================================
        // Colonne de droite:
 
        // Suppression du rappel de la charte à droite
        removeElement("//div[@id='colonneDroite']/div/div/h2[text()='Extraits de la charte']/ancestor::div[1]");
 
 
        //======================================================================
        // Général:
 
        // On supprime toutes les images (sauf pour l'édition du message)
        //removeElement("//img[@src!='/images/ccmlink.png' and @src!='/images/g.gif' and @src!='/images/i.gif' and @src!='/images/s.gif' and @src!='/images/code.gif']");
 
        // Retirer la popup CSS qui s'affiche quand on saisie le message
        removeAttributeOfElement('onfocus',"//textarea[@name='message']");
        removeAttributeOfElement('onblur',"//textarea[@name='message']");
 
        // Retirer la popup CSS qui s'affiche quand on saisie le titre
        removeAttributeOfElement('onfocus',"//input[@name='titre']");
        removeAttributeOfElement('onblur',"//input[@name='titre']");
 
        // Supprimer les couleurs:
        injectCSS('* { color: None !important; background: None !important; background-color: None !important; }');
        removeAttributeOfElement('bgcolor',"//td");
        removeAttributeOfElement('bgcolor',"//table");
 
        // Permettre aux boites de dialog CSS de s'afficher quand même avec un fond
        // (sinon elles sont transparentes ; pas pratique !)
 
        */
        // Mettez votre code ici. Quelques exemple:
 
        // forcer le fond blanc sur un site:
        injectCSS('body { background-color:white !important; }');
 
        // supprimer les couleurs des tableaux:
        removeAttributeOfElement('bgcolor',"//td");
        removeAttributeOfElement('bgcolor',"//table");
 
        // forcer la largeur d'un textarea:
        setAttributeOfElement('cols','120',"//textarea[@name='message']");  
 
    }
    catch (e)
    {
        alert("UserScript exception:\n" + e);
    }
 
})();
greasemonkey.1368553550.txt.gz · Dernière modification : 2014/07/12 12:26 (modification externe)