PROJET AUTOBLOG


Planet-Libre

source: Planet-Libre

⇐ retour index

Progi1984 : Créer une miniature d’un site web adaptatif via PhantomJS et SlimerJS

lundi 30 septembre 2013 à 10:30

Un site doit désormais s’adapter à différents phériphériques que ce soit un terminal mobile, un ordinateur, une tablette ou un écran de télévision. La technologie dite de Responsive Design est là pour cela. Afin de tester un site aux différents points de rupture, il me fallait trouver une technique et automatiser ces tests : PhantomJS (Chrome) et SlimerJS (Firefox) sont les solutions.

PhantomJS : Installation

$ wget https://phantomjs.googlecode.com/files/phantomjs-1.9.2-linux-x86_64.tar.bz2
--2013-09-23 19:46:15--  https://phantomjs.googlecode.com/files/phantomjs-1.9.2-linux-x86_64.tar.bz2
Résolution de phantomjs.googlecode.com (phantomjs.googlecode.com)... 173.194.66.82, 2a00:1450:400c:c03::52
Connexion vers phantomjs.googlecode.com (phantomjs.googlecode.com)|173.194.66.82|:443...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 13279068 (13M) [application/x-bzip2]
Sauvegarde en : «phantomjs-1.9.2-linux-x86_64.tar.bz2»

100%[===========================================================================================================================================================================>] 13 279 068  1,39MB/s   ds 9,3s   

2013-09-23 19:46:25 (1,36 MB/s) - «phantomjs-1.9.2-linux-x86_64.tar.bz2» sauvegardé [13279068/13279068]

$ tar xf phantomjs-1.9.2-linux-x86_64.tar.bz2 phantomjs-1.9.2-linux-x86_64/

$ cp phantomjs-1.9.2-linux-x86_64/bin/phantomjs /usr/local/bin/
cp: impossible de créer le fichier standard « /usr/local/bin/phantomjs »: Permission non accordée
$ sudo !!
sudo cp phantomjs-1.9.2-linux-x86_64/bin/phantomjs /usr/local/bin/
[sudo] password for franck:

PhantomJS : Script

Voici un script de base qui va vous permettre de faire un screenshot d’une site en 1024*768 et de l’exporter vers un fichier PNG.

/*
    requires: phantomjs
    usage: phantomjs screenshot.js
*/
var page = new WebPage(),
    url, filename;

if (phantom.args.length < 2) {
    console.log('Usage: screenshot.js URL filename');
    phantom.exit();
} else {
    url = phantom.args[0];
    filename = phantom.args[1];

    page.viewportSize = { width: 1024, height: 768 };

    page.open(url, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            window.setTimeout(function () {PhantomJS
                page.render(page.viewportSize.width + 'x' + page.viewportSize.height +'_'+ filename);
                phantom.exit();
            }, 2000);
        }
    });
}

Malheureusement, on a qu’une seule taille de viewport, il en faudrait plusieurs afin de tout tester.
Modifions ce script pour gérer plusieurs viewports.

/*
    requires: phantomjs
    usage: phantomjs screenshot.js URL
*/
var sizes = [
        [320, 480],
        [320, 568],
        [600, 1024],
        [1024, 768],
        [1280, 800],
        [1440, 900]
    ],
    count, url, filename;

if (phantom.args.length < 1) {
    console.log('Usage: screenshot.js URL');
    phantom.exit();
} else {
   url = phantom.args[0];
   var filename = url.replace('http://','');
   filename = filename.replace('www.','');
   filename = filename.replace(/\\./g,'_');
   filename = filename.replace(/\\//g,'_');
   count = 0;
   sizes.forEach(function(vpSize){
    count++;
    var page = new WebPage();
    page.viewportSize = { width: vpSize[0], height: vpSize[1] };
    page.open(url, function (status) {
      if (status !== 'success') {
        console.log('Unable to load the address!');
      } else {

        window.setTimeout(function () {
          page.render(filename+'_'+page.viewportSize.width+ 'x' + page.viewportSize.height +'.png');
          page.close();
          count--;
          if(count == 0){
            phantom.exit();
          }
        }, 2000);
      }
    });
  });
}

PhantomJS : Exemple

Pour l’utiliser, la commande est simple :

$ phantomjs screenshot.js http://rootslabs.net/blog/

Et hop, cela vous génère vos 6 screenshots de votre site :
PhantomJS : Screenshot RootsLabs

Il reste un souci ; PhantomJS permet le rendu sous le moteur de Chrome. Mais comment faire pour le moteur de Firefox ?
La solution s’appelle SlimerJS.

SlimerJS : Installation

SlimerJS : Script

Ensuite, je teste mon précédent script pour l’adapter à SlimerJS.

Je remplace

var page = new WebPage();

par

var page = require("webpage").create();

Pourquoi ? L’objet Webpage est marqué “deprecated” dans PhantomJS (Merci LaurentJ).
Le code devient ainsi fonctionnel et valide sur PhantomJS et SlimerJS.

Et j’adapte le code pour détecter le moteur utilisé :

/*
    requires: phantomjs
    usage: phantomjs screenshot.js URL
*/
var sizes = [
        [320, 480],
        [320, 568],
        [600, 1024],
        [1024, 768],
        [1280, 800],
        [1440, 900]
    ],
    count, url, filename;
if(typeof(slimer) != 'undefined'){
  var sEngine = 'slimerjs';
} else {
  var sEngine = 'phantomjs';
}
if (phantom.args.length < 1) {
    console.log('Usage: screenshot.js URL');
    phantom.exit();
} else {
   url = phantom.args[0];
   var filename = url.replace('http://','');
   filename = filename.replace('www.','');
   filename = filename.replace(/\\./g,'_');
   filename = filename.replace(/\\//g,'_');
   count = 0;
   sizes.forEach(function(vpSize){
    count++;
    //var page = new WebPage();
    var page = require("webpage").create();
    page.viewportSize = { width: vpSize[0], height: vpSize[1] };
    page.open(url, function (status) {
      if (status !== 'success') {
        console.log('Unable to load the address!');
      } else {

        window.setTimeout(function () {
          page.render(filename+'_'+page.viewportSize.width+ 'x' + page.viewportSize.height + '_' + sEngine +'.png');
          page.close();
          count--;
          if(count == 0){
            phantom.exit();
          }
        }, 2000);
      }
    });
  });
}

SlimerJS : Exemple

Pour l’utiliser, la commande est simple :

$ xvfb-run ./slimerjs screenshot.js http://rootslabs.net/blog/

Conclusion

Dorénavant, via les deux commandes suivantes, il vous est possible de tester votre responsive design en ligne de commande et ainsi voir les anomalies sur un navigateur ou un autre rapidement.
PhantomJS (moteur de Chrome) :

$ phantomjs screenshot.js http://rootslabs.net/blog/

SlimerJS (moteur de Firefox) :

$ xvfb-run ./slimerjs screenshot.js http://rootslabs.net/blog/

Cet article Créer une miniature d’un site web adaptatif via PhantomJS et SlimerJS est apparu en premier sur RootsLabs.

Gravatar de Progi1984
Original post of Progi1984.Votez pour ce billet sur Planet Libre.

Articles similaires