charactersCount.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Lists the number of different characters
  3. */
  4. /* global document: true, Node: true, window: true */
  5. exports.version = '1.0';
  6. exports.module = function(phantomas) {
  7. 'use strict';
  8. //phantomas.setMetric('differentCharacters'); // @desc the number of different characters in the body @offenders
  9. phantomas.on('report', function() {
  10. phantomas.log("charactersCount: starting to analyze characters on page...");
  11. phantomas.evaluate(function() {
  12. (function(phantomas) {
  13. phantomas.spyEnabled(false, 'analyzing characters on page');
  14. function getLetterCount(arr){
  15. return arr.reduce(function(prev, next){
  16. prev[next] = 1;
  17. return prev;
  18. }, {});
  19. }
  20. if (document.body && document.body.textContent) {
  21. var allText = '';
  22. // Traverse all DOM Tree to read text
  23. var runner = new phantomas.nodeRunner();
  24. runner.walk(document.body, function(node, depth) {
  25. switch (node.nodeType) {
  26. // Grabing text nodes
  27. case Node.TEXT_NODE:
  28. if (node.parentNode.tagName !== 'SCRIPT' && node.parentNode.tagName !== 'STYLE') {
  29. allText += node.nodeValue;
  30. }
  31. break;
  32. // Grabing CSS content properties
  33. case Node.ELEMENT_NODE:
  34. if (node.tagName !== 'SCRIPT' && node.tagName !== 'STYLE') {
  35. allText += window.getComputedStyle(node).getPropertyValue('content');
  36. allText += window.getComputedStyle(node, ':before').getPropertyValue('content');
  37. allText += window.getComputedStyle(node, ':after').getPropertyValue('content');
  38. }
  39. break;
  40. }
  41. });
  42. // Reduce all text found in page into a string of unique chars
  43. var charactersList = getLetterCount(allText.split(''));
  44. var charsetString = Object.keys(charactersList).sort().join('');
  45. // Remove blank characters
  46. charsetString = charsetString.replace(/\s/g, '');
  47. phantomas.setMetric('differentCharacters', charsetString.length);
  48. phantomas.addOffender('differentCharacters', charsetString);
  49. }
  50. phantomas.spyEnabled(true);
  51. }(window.__phantomas));
  52. });
  53. phantomas.log("charactersCount: analyzing characters done.");
  54. });
  55. };