browser_getScreenshots.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. // a blue page
  6. const TEST_URL = "https://example.com/browser/browser/components/newtab/test/browser/blue_page.html";
  7. const XHTMLNS = "http://www.w3.org/1999/xhtml";
  8. ChromeUtils.defineModuleGetter(this, "Screenshots", "resource://activity-stream/lib/Screenshots.jsm");
  9. function get_pixels_for_blob(blob, width, height) {
  10. return new Promise(resolve => {
  11. // get the pixels out of the screenshot that we just took
  12. let img = document.createElementNS(XHTMLNS, "img");
  13. let imgPath = URL.createObjectURL(blob);
  14. img.setAttribute("src", imgPath);
  15. img.addEventListener("load", () => {
  16. let canvas = document.createElementNS(XHTMLNS, "canvas");
  17. canvas.setAttribute("width", width);
  18. canvas.setAttribute("height", height);
  19. let ctx = canvas.getContext("2d");
  20. ctx.drawImage(img, 0, 0, width, height);
  21. const result = ctx.getImageData(0, 0, width, height).data;
  22. URL.revokeObjectURL(imgPath);
  23. resolve(result);
  24. }, {once: true});
  25. });
  26. }
  27. add_task(async function test_screenshot() {
  28. await SpecialPowers.pushPrefEnv({set: [["browser.pagethumbnails.capturing_disabled", false]]});
  29. // take a screenshot of a blue page and save it as a blob
  30. const screenshotAsObject = await Screenshots.getScreenshotForURL(TEST_URL);
  31. let pixels = await get_pixels_for_blob(screenshotAsObject.data, 10, 10);
  32. let rgbaCount = {r: 0, g: 0, b: 0, a: 0};
  33. while (pixels.length) {
  34. // break the pixels into arrays of 4 components [red, green, blue, alpha]
  35. let [r, g, b, a, ...rest] = pixels;
  36. pixels = rest;
  37. // count the number of each coloured pixels
  38. if (r === 255) { rgbaCount.r += 1; }
  39. if (g === 255) { rgbaCount.g += 1; }
  40. if (b === 255) { rgbaCount.b += 1; }
  41. if (a === 255) { rgbaCount.a += 1; }
  42. }
  43. // in the end, we should only have 100 blue pixels (10 x 10) with full opacity
  44. Assert.equal(rgbaCount.b, 100, "Has 100 blue pixels");
  45. Assert.equal(rgbaCount.a, 100, "Has full opacity");
  46. Assert.equal(rgbaCount.r, 0, "Does not have any red pixels");
  47. Assert.equal(rgbaCount.g, 0, "Does not have any green pixels");
  48. });