summaryrefslogtreecommitdiffstats
path: root/browser/extensions/screenshots/background/takeshot.js
blob: c8e229247bdaad2df3ec28cdde3971befc837f43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/* globals browser, communication, getZoomFactor, shot, main, catcher, analytics, blobConverters, thumbnailGenerator */

"use strict";

this.takeshot = (function () {
  const exports = {};
  const MAX_CANVAS_DIMENSION = 32767;

  communication.register(
    "screenshotPage",
    (sender, selectedPos, screenshotType, devicePixelRatio) => {
      return screenshotPage(selectedPos, screenshotType, devicePixelRatio);
    }
  );

  communication.register("getZoomFactor", sender => {
    return getZoomFactor();
  });

  function screenshotPage(pos, screenshotType, devicePixelRatio) {
    pos.width = Math.min(pos.right - pos.left, MAX_CANVAS_DIMENSION);
    pos.height = Math.min(pos.bottom - pos.top, MAX_CANVAS_DIMENSION);

    // If we are printing the full page or a truncated full page,
    // we must pass in this rectangle to preview the entire image
    let options = { format: "png" };
    if (
      screenshotType === "fullPage" ||
      screenshotType === "fullPageTruncated"
    ) {
      let rectangle = {
        x: 0,
        y: 0,
        width: pos.width,
        height: pos.height,
      };
      options.rect = rectangle;
      options.resetScrollPosition = true;
    } else if (screenshotType != "visible") {
      let rectangle = {
        x: pos.left,
        y: pos.top,
        width: pos.width,
        height: pos.height,
      };
      options.rect = rectangle;
    }

    return catcher.watchPromise(
      browser.tabs.captureTab(null, options).then(dataUrl => {
        const image = new Image();
        image.src = dataUrl;
        return new Promise((resolve, reject) => {
          image.onload = catcher.watchFunction(() => {
            const xScale = devicePixelRatio;
            const yScale = devicePixelRatio;
            const canvas = document.createElement("canvas");
            canvas.height = pos.height * yScale;
            canvas.width = pos.width * xScale;
            const context = canvas.getContext("2d");
            context.drawImage(
              image,
              0,
              0,
              pos.width * xScale,
              pos.height * yScale,
              0,
              0,
              pos.width * xScale,
              pos.height * yScale
            );
            const result = canvas.toDataURL();
            resolve(result);
          });
        });
      })
    );
  }

  return exports;
})();