axe-puppeteer.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const puppeteer = require('puppeteer');
  2. const axeCore = require('axe-core');
  3. const { parse: parseURL } = require('url');
  4. const assert = require('assert');
  5. // Cheap URL validation
  6. const isValidURL = input => {
  7. const u = parseURL(input);
  8. return u.protocol && u.host;
  9. };
  10. // node axe-puppeteer.js <url>
  11. const url = process.argv[2];
  12. assert(isValidURL(url), 'Invalid URL');
  13. const main = async url => {
  14. let browser;
  15. let results;
  16. try {
  17. // Setup Puppeteer
  18. browser = await puppeteer.launch();
  19. // Get new page
  20. const page = await browser.newPage();
  21. await page.goto(url);
  22. // Inject and run axe-core
  23. const handle = await page.evaluateHandle(`
  24. // Inject axe source code
  25. ${axeCore.source}
  26. // Run axe
  27. axe.run()
  28. `);
  29. // Get the results from `axe.run()`.
  30. results = await handle.jsonValue();
  31. // Destroy the handle & return axe results.
  32. await handle.dispose();
  33. } catch (err) {
  34. // Ensure we close the puppeteer connection when possible
  35. if (browser) {
  36. await browser.close();
  37. }
  38. // Re-throw
  39. throw err;
  40. }
  41. await browser.close();
  42. return results;
  43. };
  44. main(url)
  45. .then(results => {
  46. console.log(results);
  47. })
  48. .catch(err => {
  49. console.error('Error running axe-core:', err.message);
  50. process.exit(1);
  51. });