jsdom.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global require, exports, Buffer */
  24. const { URL } = require("url");
  25. const fs = require("fs");
  26. const crypto = require("crypto");
  27. const { JSDOM, VirtualConsole } = require("jsdom");
  28. const dataUri = require("strong-data-uri");
  29. const iconv = require("iconv-lite");
  30. const request = require("request-promise-native");
  31. const SCRIPTS = [
  32. "../../lib/frame-tree/frame-tree.js",
  33. "../../lib/single-file/util/doc-util.js",
  34. "../../lib/single-file/util/doc-helper.js",
  35. "../../lib/single-file/util/timeout.js",
  36. "../../lib/single-file/vendor/css-tree.js",
  37. "../../lib/single-file/vendor/html-srcset-parser.js",
  38. "../../lib/single-file/vendor/css-minifier.js",
  39. "../../lib/single-file/vendor/css-font-property-parser.js",
  40. "../../lib/single-file/vendor/css-media-query-parser.js",
  41. "../../lib/single-file/modules/html-minifier.js",
  42. "../../lib/single-file/modules/css-fonts-minifier.js",
  43. "../../lib/single-file/modules/css-fonts-alt-minifier.js",
  44. "../../lib/single-file/modules/css-matched-rules.js",
  45. "../../lib/single-file/modules/css-medias-alt-minifier.js",
  46. "../../lib/single-file/modules/css-rules-minifier.js",
  47. "../../lib/single-file/modules/html-images-alt-minifier.js",
  48. "../../lib/single-file/modules/html-serializer.js",
  49. "../../lib/single-file/single-file-core.js"
  50. ];
  51. exports.getPageData = async options => {
  52. const pageContent = (await request({
  53. method: "GET",
  54. uri: options.url,
  55. resolveWithFullResponse: true,
  56. encoding: null,
  57. headers: {
  58. "User-Agent": options.userAgent
  59. }
  60. })).body.toString();
  61. const jsdomOptions = {
  62. url: options.url,
  63. virtualConsole: new VirtualConsole(),
  64. userAgent: options.userAgent,
  65. pretendToBeVisual: true,
  66. runScripts: "outside-only",
  67. resources: "usable"
  68. };
  69. if (options.browserWidth && options.browserHeight) {
  70. jsdomOptions.beforeParse = function (window) {
  71. window.outerWidth = window.innerWidth = options.browserWidth;
  72. window.outerHeight = window.innerHeight = options.browserHeight;
  73. };
  74. }
  75. let dom;
  76. try {
  77. dom = new JSDOM(pageContent, jsdomOptions);
  78. const win = dom.window;
  79. const doc = win.document;
  80. const scripts = (await Promise.all(SCRIPTS.map(scriptPath => fs.readFileSync(require.resolve(scriptPath)).toString()))).join("\n");
  81. dom.window.eval(scripts);
  82. if (dom.window.document.readyState == "loading") {
  83. await new Promise(resolve => win.document.onload = resolve);
  84. }
  85. win.Element.prototype.getBoundingClientRect = undefined;
  86. executeFrameScripts(doc, scripts);
  87. if (!options.saveRawPage && !options.removeFrames) {
  88. options.framesData = await win.frameTree.getAsync(options);
  89. }
  90. options.win = win;
  91. options.doc = doc;
  92. const SingleFile = getSingleFileClass(win);
  93. const singleFile = new SingleFile(options);
  94. await singleFile.initialize();
  95. await singleFile.run();
  96. return singleFile.getPageData();
  97. } finally {
  98. if (dom && dom.window) {
  99. dom.window.close();
  100. }
  101. }
  102. };
  103. function executeFrameScripts(doc, scripts) {
  104. const frameElements = doc.querySelectorAll("iframe, frame");
  105. frameElements.forEach(frameElement => {
  106. try {
  107. frameElement.contentWindow.Element.prototype.getBoundingClientRect = undefined;
  108. frameElement.contentWindow.eval(scripts);
  109. executeFrameScripts(frameElement.contentDocument, scripts);
  110. } catch (error) {
  111. // ignored
  112. }
  113. });
  114. }
  115. function getSingleFileClass(win) {
  116. const docHelper = win.docHelper;
  117. const modules = {
  118. docHelper: docHelper,
  119. srcsetParser: win.srcsetParser,
  120. cssMinifier: win.cssMinifier,
  121. htmlMinifier: win.htmlMinifier,
  122. serializer: win.serializer,
  123. fontsMinifier: win.fontsMinifier.getInstance(win.cssTree, win.fontPropertyParser, docHelper),
  124. fontsAltMinifier: win.fontsAltMinifier.getInstance(win.cssTree),
  125. cssRulesMinifier: win.cssRulesMinifier.getInstance(win.cssTree),
  126. matchedRules: win.matchedRules.getInstance(win.cssTree),
  127. mediasAltMinifier: win.mediasAltMinifier.getInstance(win.cssTree, win.mediaQueryParser),
  128. imagesAltMinifier: win.imagesAltMinifier.getInstance(win.srcsetParser)
  129. };
  130. const domUtil = {
  131. getResourceContent,
  132. parseDocContent,
  133. parseSVGContent,
  134. isValidFontUrl,
  135. getContentSize,
  136. digestText,
  137. parseURL
  138. };
  139. return win.SingleFileCore.getClass(win.docUtil.getInstance(modules, domUtil), win.cssTree);
  140. }
  141. function parseDocContent(content) {
  142. return (new JSDOM(content, {
  143. contentType: "text/html"
  144. })).window.document;
  145. }
  146. function parseSVGContent(content) {
  147. return (new JSDOM(content, {
  148. contentType: "image/svg+xml"
  149. })).window.document;
  150. }
  151. async function digestText(algo, text) {
  152. const hash = crypto.createHash(algo.replace("-", "").toLowerCase());
  153. hash.update(text, "utf-8");
  154. return hash.digest("hex");
  155. }
  156. function getContentSize(content) {
  157. return Buffer.byteLength(content, "utf-8");
  158. }
  159. function isValidFontUrl(/* urlFunction */) {
  160. // TODO?
  161. return true;
  162. }
  163. async function getResourceContent(resourceURL, options) {
  164. const resourceContent = await request({
  165. method: "GET",
  166. uri: resourceURL,
  167. resolveWithFullResponse: true,
  168. encoding: null,
  169. headers: {
  170. "User-Agent": options.userAgent
  171. }
  172. });
  173. return {
  174. getUrl() {
  175. return resourceContent.request.href;
  176. },
  177. getContentType() {
  178. return resourceContent.headers["content-type"];
  179. },
  180. getStatusCode() {
  181. return resourceContent.statusCode;
  182. },
  183. getSize() {
  184. return resourceContent.body.byteLength;
  185. },
  186. getText(charset) {
  187. return iconv.decode(resourceContent.body, charset);
  188. },
  189. async getDataUri(contentType) {
  190. return dataUri.encode(resourceContent.body, contentType || this.getContentType());
  191. }
  192. };
  193. }
  194. function parseURL(resourceURL, baseURI) {
  195. return new URL(resourceURL, baseURI);
  196. }