document-cloner.js 24 KB

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