document-cloner.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. var __generator = (this && this.__generator) || function (thisArg, body) {
  12. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  13. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  14. function verb(n) { return function (v) { return step([n, v]); }; }
  15. function step(op) {
  16. if (f) throw new TypeError("Generator is already executing.");
  17. while (_) try {
  18. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  19. if (y = 0, t) op = [op[0] & 2, t.value];
  20. switch (op[0]) {
  21. case 0: case 1: t = op; break;
  22. case 4: _.label++; return { value: op[1], done: false };
  23. case 5: _.label++; y = op[1]; op = [0]; continue;
  24. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  25. default:
  26. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  27. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  28. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  29. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  30. if (t[2]) _.ops.pop();
  31. _.trys.pop(); continue;
  32. }
  33. op = body.call(thisArg, _);
  34. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  35. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  36. }
  37. };
  38. Object.defineProperty(exports, "__esModule", { value: true });
  39. exports.copyCSSStyles = exports.DocumentCloner = void 0;
  40. var node_parser_1 = require("./node-parser");
  41. var parser_1 = require("../css/syntax/parser");
  42. var counter_1 = require("../css/types/functions/counter");
  43. var list_style_type_1 = require("../css/property-descriptors/list-style-type");
  44. var index_1 = require("../css/index");
  45. var quotes_1 = require("../css/property-descriptors/quotes");
  46. var debugger_1 = require("../core/debugger");
  47. var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
  48. var DocumentCloner = /** @class */ (function () {
  49. function DocumentCloner(context, element, options) {
  50. this.context = context;
  51. this.options = options;
  52. this.scrolledElements = [];
  53. this.referenceElement = element;
  54. this.counters = new counter_1.CounterState();
  55. this.quoteDepth = 0;
  56. if (!element.ownerDocument) {
  57. throw new Error('Cloned element does not have an owner document');
  58. }
  59. this.documentElement = this.cloneNode(element.ownerDocument.documentElement);
  60. }
  61. DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) {
  62. var _this = this;
  63. var iframe = createIFrameContainer(ownerDocument, windowSize);
  64. if (!iframe.contentWindow) {
  65. return Promise.reject("Unable to find iframe window");
  66. }
  67. var scrollX = ownerDocument.defaultView.pageXOffset;
  68. var scrollY = ownerDocument.defaultView.pageYOffset;
  69. var cloneWindow = iframe.contentWindow;
  70. var documentClone = cloneWindow.document;
  71. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  72. if window url is about:blank, we can assign the url to current by writing onto the document
  73. */
  74. var iframeLoad = iframeLoader(iframe).then(function () { return __awaiter(_this, void 0, void 0, function () {
  75. var onclone, referenceElement;
  76. return __generator(this, function (_a) {
  77. switch (_a.label) {
  78. case 0:
  79. this.scrolledElements.forEach(restoreNodeScroll);
  80. if (cloneWindow) {
  81. cloneWindow.scrollTo(windowSize.left, windowSize.top);
  82. if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) &&
  83. (cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)) {
  84. this.context.logger.warn('Unable to restore scroll position for cloned document');
  85. this.context.windowBounds = this.context.windowBounds.add(cloneWindow.scrollX - windowSize.left, cloneWindow.scrollY - windowSize.top, 0, 0);
  86. }
  87. }
  88. onclone = this.options.onclone;
  89. referenceElement = this.clonedReferenceElement;
  90. if (typeof referenceElement === 'undefined') {
  91. return [2 /*return*/, Promise.reject("Error finding the " + this.referenceElement.nodeName + " in the cloned document")];
  92. }
  93. if (!(documentClone.fonts && documentClone.fonts.ready)) return [3 /*break*/, 2];
  94. return [4 /*yield*/, documentClone.fonts.ready];
  95. case 1:
  96. _a.sent();
  97. _a.label = 2;
  98. case 2:
  99. if (!/(AppleWebKit)/g.test(navigator.userAgent)) return [3 /*break*/, 4];
  100. return [4 /*yield*/, imagesReady(documentClone)];
  101. case 3:
  102. _a.sent();
  103. _a.label = 4;
  104. case 4:
  105. if (typeof onclone === 'function') {
  106. return [2 /*return*/, Promise.resolve()
  107. .then(function () { return onclone(documentClone, referenceElement); })
  108. .then(function () { return iframe; })];
  109. }
  110. return [2 /*return*/, iframe];
  111. }
  112. });
  113. }); });
  114. documentClone.open();
  115. documentClone.write(serializeDoctype(document.doctype) + "<html></html>");
  116. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  117. restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);
  118. documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);
  119. documentClone.close();
  120. return iframeLoad;
  121. };
  122. DocumentCloner.prototype.createElementClone = function (node) {
  123. if (debugger_1.isDebugging(node, 2 /* CLONE */)) {
  124. debugger;
  125. }
  126. if (node_parser_1.isCanvasElement(node)) {
  127. return this.createCanvasClone(node);
  128. }
  129. if (node_parser_1.isStyleElement(node)) {
  130. return this.createStyleClone(node);
  131. }
  132. var clone = node.cloneNode(false);
  133. if (node_parser_1.isImageElement(clone)) {
  134. if (node_parser_1.isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) {
  135. clone.src = node.currentSrc;
  136. clone.srcset = '';
  137. }
  138. if (clone.loading === 'lazy') {
  139. clone.loading = 'eager';
  140. }
  141. }
  142. return clone;
  143. };
  144. DocumentCloner.prototype.createStyleClone = function (node) {
  145. try {
  146. var sheet = node.sheet;
  147. if (sheet && sheet.cssRules) {
  148. var css = [].slice.call(sheet.cssRules, 0).reduce(function (css, rule) {
  149. if (rule && typeof rule.cssText === 'string') {
  150. return css + rule.cssText;
  151. }
  152. return css;
  153. }, '');
  154. var style = node.cloneNode(false);
  155. style.textContent = css;
  156. return style;
  157. }
  158. }
  159. catch (e) {
  160. // accessing node.sheet.cssRules throws a DOMException
  161. this.context.logger.error('Unable to access cssRules property', e);
  162. if (e.name !== 'SecurityError') {
  163. throw e;
  164. }
  165. }
  166. return node.cloneNode(false);
  167. };
  168. DocumentCloner.prototype.createCanvasClone = function (canvas) {
  169. var _a;
  170. if (this.options.inlineImages && canvas.ownerDocument) {
  171. var img = canvas.ownerDocument.createElement('img');
  172. try {
  173. img.src = canvas.toDataURL();
  174. return img;
  175. }
  176. catch (e) {
  177. this.context.logger.info("Unable to inline canvas contents, canvas is tainted", canvas);
  178. }
  179. }
  180. var clonedCanvas = canvas.cloneNode(false);
  181. try {
  182. clonedCanvas.width = canvas.width;
  183. clonedCanvas.height = canvas.height;
  184. var ctx = canvas.getContext('2d');
  185. var clonedCtx = clonedCanvas.getContext('2d');
  186. if (clonedCtx) {
  187. if (!this.options.allowTaint && ctx) {
  188. clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  189. }
  190. else {
  191. var gl = (_a = canvas.getContext('webgl2')) !== null && _a !== void 0 ? _a : canvas.getContext('webgl');
  192. if (gl) {
  193. var attribs = gl.getContextAttributes();
  194. if ((attribs === null || attribs === void 0 ? void 0 : attribs.preserveDrawingBuffer) === false) {
  195. this.context.logger.warn('Unable to clone WebGL context as it has preserveDrawingBuffer=false', canvas);
  196. }
  197. }
  198. clonedCtx.drawImage(canvas, 0, 0);
  199. }
  200. }
  201. return clonedCanvas;
  202. }
  203. catch (e) {
  204. this.context.logger.info("Unable to clone canvas as it is tainted", canvas);
  205. }
  206. return clonedCanvas;
  207. };
  208. DocumentCloner.prototype.cloneNode = function (node) {
  209. if (node_parser_1.isTextNode(node)) {
  210. return document.createTextNode(node.data);
  211. }
  212. if (!node.ownerDocument) {
  213. return node.cloneNode(false);
  214. }
  215. var window = node.ownerDocument.defaultView;
  216. if (window && node_parser_1.isElementNode(node) && (node_parser_1.isHTMLElementNode(node) || node_parser_1.isSVGElementNode(node))) {
  217. var clone = this.createElementClone(node);
  218. clone.style.transitionProperty = 'none';
  219. var style = window.getComputedStyle(node);
  220. var styleBefore = window.getComputedStyle(node, ':before');
  221. var styleAfter = window.getComputedStyle(node, ':after');
  222. if (this.referenceElement === node && node_parser_1.isHTMLElementNode(clone)) {
  223. this.clonedReferenceElement = clone;
  224. }
  225. if (node_parser_1.isBodyElement(clone)) {
  226. createPseudoHideStyles(clone);
  227. }
  228. var counters = this.counters.parse(new index_1.CSSParsedCounterDeclaration(this.context, style));
  229. var before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE);
  230. for (var child = node.firstChild; child; child = child.nextSibling) {
  231. if (!node_parser_1.isElementNode(child) ||
  232. (!node_parser_1.isScriptElement(child) &&
  233. !child.hasAttribute(IGNORE_ATTRIBUTE) &&
  234. (typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))) {
  235. if (!this.options.copyStyles || !node_parser_1.isElementNode(child) || !node_parser_1.isStyleElement(child)) {
  236. clone.appendChild(this.cloneNode(child));
  237. }
  238. }
  239. }
  240. if (before) {
  241. clone.insertBefore(before, clone.firstChild);
  242. }
  243. var after = this.resolvePseudoContent(node, clone, styleAfter, PseudoElementType.AFTER);
  244. if (after) {
  245. clone.appendChild(after);
  246. }
  247. this.counters.pop(counters);
  248. if (style && (this.options.copyStyles || node_parser_1.isSVGElementNode(node)) && !node_parser_1.isIFrameElement(node)) {
  249. exports.copyCSSStyles(style, clone);
  250. }
  251. if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
  252. this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
  253. }
  254. if ((node_parser_1.isTextareaElement(node) || node_parser_1.isSelectElement(node)) &&
  255. (node_parser_1.isTextareaElement(clone) || node_parser_1.isSelectElement(clone))) {
  256. clone.value = node.value;
  257. }
  258. return clone;
  259. }
  260. return node.cloneNode(false);
  261. };
  262. DocumentCloner.prototype.resolvePseudoContent = function (node, clone, style, pseudoElt) {
  263. var _this = this;
  264. if (!style) {
  265. return;
  266. }
  267. var value = style.content;
  268. var document = clone.ownerDocument;
  269. if (!document || !value || value === 'none' || value === '-moz-alt-content' || style.display === 'none') {
  270. return;
  271. }
  272. this.counters.parse(new index_1.CSSParsedCounterDeclaration(this.context, style));
  273. var declaration = new index_1.CSSParsedPseudoDeclaration(this.context, style);
  274. var anonymousReplacedElement = document.createElement('html2canvaspseudoelement');
  275. exports.copyCSSStyles(style, anonymousReplacedElement);
  276. declaration.content.forEach(function (token) {
  277. if (token.type === 0 /* STRING_TOKEN */) {
  278. anonymousReplacedElement.appendChild(document.createTextNode(token.value));
  279. }
  280. else if (token.type === 22 /* URL_TOKEN */) {
  281. var img = document.createElement('img');
  282. img.src = token.value;
  283. img.style.opacity = '1';
  284. anonymousReplacedElement.appendChild(img);
  285. }
  286. else if (token.type === 18 /* FUNCTION */) {
  287. if (token.name === 'attr') {
  288. var attr = token.values.filter(parser_1.isIdentToken);
  289. if (attr.length) {
  290. anonymousReplacedElement.appendChild(document.createTextNode(node.getAttribute(attr[0].value) || ''));
  291. }
  292. }
  293. else if (token.name === 'counter') {
  294. var _a = token.values.filter(parser_1.nonFunctionArgSeparator), counter = _a[0], counterStyle = _a[1];
  295. if (counter && parser_1.isIdentToken(counter)) {
  296. var counterState = _this.counters.getCounterValue(counter.value);
  297. var counterType = counterStyle && parser_1.isIdentToken(counterStyle)
  298. ? list_style_type_1.listStyleType.parse(_this.context, counterStyle.value)
  299. : 3 /* DECIMAL */;
  300. anonymousReplacedElement.appendChild(document.createTextNode(counter_1.createCounterText(counterState, counterType, false)));
  301. }
  302. }
  303. else if (token.name === 'counters') {
  304. var _b = token.values.filter(parser_1.nonFunctionArgSeparator), counter = _b[0], delim = _b[1], counterStyle = _b[2];
  305. if (counter && parser_1.isIdentToken(counter)) {
  306. var counterStates = _this.counters.getCounterValues(counter.value);
  307. var counterType_1 = counterStyle && parser_1.isIdentToken(counterStyle)
  308. ? list_style_type_1.listStyleType.parse(_this.context, counterStyle.value)
  309. : 3 /* DECIMAL */;
  310. var separator = delim && delim.type === 0 /* STRING_TOKEN */ ? delim.value : '';
  311. var text = counterStates
  312. .map(function (value) { return counter_1.createCounterText(value, counterType_1, false); })
  313. .join(separator);
  314. anonymousReplacedElement.appendChild(document.createTextNode(text));
  315. }
  316. }
  317. else {
  318. // console.log('FUNCTION_TOKEN', token);
  319. }
  320. }
  321. else if (token.type === 20 /* IDENT_TOKEN */) {
  322. switch (token.value) {
  323. case 'open-quote':
  324. anonymousReplacedElement.appendChild(document.createTextNode(quotes_1.getQuote(declaration.quotes, _this.quoteDepth++, true)));
  325. break;
  326. case 'close-quote':
  327. anonymousReplacedElement.appendChild(document.createTextNode(quotes_1.getQuote(declaration.quotes, --_this.quoteDepth, false)));
  328. break;
  329. default:
  330. // safari doesn't parse string tokens correctly because of lack of quotes
  331. anonymousReplacedElement.appendChild(document.createTextNode(token.value));
  332. }
  333. }
  334. });
  335. anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  336. var newClassName = pseudoElt === PseudoElementType.BEFORE
  337. ? " " + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE
  338. : " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  339. if (node_parser_1.isSVGElementNode(clone)) {
  340. clone.className.baseValue += newClassName;
  341. }
  342. else {
  343. clone.className += newClassName;
  344. }
  345. return anonymousReplacedElement;
  346. };
  347. DocumentCloner.destroy = function (container) {
  348. if (container.parentNode) {
  349. container.parentNode.removeChild(container);
  350. return true;
  351. }
  352. return false;
  353. };
  354. return DocumentCloner;
  355. }());
  356. exports.DocumentCloner = DocumentCloner;
  357. var PseudoElementType;
  358. (function (PseudoElementType) {
  359. PseudoElementType[PseudoElementType["BEFORE"] = 0] = "BEFORE";
  360. PseudoElementType[PseudoElementType["AFTER"] = 1] = "AFTER";
  361. })(PseudoElementType || (PseudoElementType = {}));
  362. var createIFrameContainer = function (ownerDocument, bounds) {
  363. var cloneIframeContainer = ownerDocument.createElement('iframe');
  364. cloneIframeContainer.className = 'html2canvas-container';
  365. cloneIframeContainer.style.visibility = 'hidden';
  366. cloneIframeContainer.style.position = 'fixed';
  367. cloneIframeContainer.style.left = '-10000px';
  368. cloneIframeContainer.style.top = '0px';
  369. cloneIframeContainer.style.border = '0';
  370. cloneIframeContainer.width = bounds.width.toString();
  371. cloneIframeContainer.height = bounds.height.toString();
  372. cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it
  373. cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true');
  374. ownerDocument.body.appendChild(cloneIframeContainer);
  375. return cloneIframeContainer;
  376. };
  377. var imageReady = function (img) {
  378. return new Promise(function (resolve) {
  379. if (img.complete) {
  380. resolve();
  381. return;
  382. }
  383. if (!img.src) {
  384. resolve();
  385. return;
  386. }
  387. img.onload = resolve;
  388. img.onerror = resolve;
  389. });
  390. };
  391. var imagesReady = function (document) {
  392. return Promise.all([].slice.call(document.images, 0).map(imageReady));
  393. };
  394. var iframeLoader = function (iframe) {
  395. return new Promise(function (resolve, reject) {
  396. var cloneWindow = iframe.contentWindow;
  397. if (!cloneWindow) {
  398. return reject("No window assigned for iframe");
  399. }
  400. var documentClone = cloneWindow.document;
  401. cloneWindow.onload = iframe.onload = function () {
  402. cloneWindow.onload = iframe.onload = null;
  403. var interval = setInterval(function () {
  404. if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
  405. clearInterval(interval);
  406. resolve(iframe);
  407. }
  408. }, 50);
  409. };
  410. });
  411. };
  412. var ignoredStyleProperties = [
  413. 'all',
  414. 'd',
  415. 'content' // Safari shows pseudoelements if content is set
  416. ];
  417. var copyCSSStyles = function (style, target) {
  418. // Edge does not provide value for cssText
  419. for (var i = style.length - 1; i >= 0; i--) {
  420. var property = style.item(i);
  421. if (ignoredStyleProperties.indexOf(property) === -1) {
  422. target.style.setProperty(property, style.getPropertyValue(property));
  423. }
  424. }
  425. return target;
  426. };
  427. exports.copyCSSStyles = copyCSSStyles;
  428. var serializeDoctype = function (doctype) {
  429. var str = '';
  430. if (doctype) {
  431. str += '<!DOCTYPE ';
  432. if (doctype.name) {
  433. str += doctype.name;
  434. }
  435. if (doctype.internalSubset) {
  436. str += doctype.internalSubset;
  437. }
  438. if (doctype.publicId) {
  439. str += "\"" + doctype.publicId + "\"";
  440. }
  441. if (doctype.systemId) {
  442. str += "\"" + doctype.systemId + "\"";
  443. }
  444. str += '>';
  445. }
  446. return str;
  447. };
  448. var restoreOwnerScroll = function (ownerDocument, x, y) {
  449. if (ownerDocument &&
  450. ownerDocument.defaultView &&
  451. (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  452. ownerDocument.defaultView.scrollTo(x, y);
  453. }
  454. };
  455. var restoreNodeScroll = function (_a) {
  456. var element = _a[0], x = _a[1], y = _a[2];
  457. element.scrollLeft = x;
  458. element.scrollTop = y;
  459. };
  460. var PSEUDO_BEFORE = ':before';
  461. var PSEUDO_AFTER = ':after';
  462. var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before';
  463. var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after';
  464. var PSEUDO_HIDE_ELEMENT_STYLE = "{\n content: \"\" !important;\n display: none !important;\n}";
  465. var createPseudoHideStyles = function (body) {
  466. createStyles(body, "." + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + "\n ." + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
  467. };
  468. var createStyles = function (body, styles) {
  469. var document = body.ownerDocument;
  470. if (document) {
  471. var style = document.createElement('style');
  472. style.textContent = styles;
  473. body.appendChild(style);
  474. }
  475. };
  476. //# sourceMappingURL=document-cloner.js.map