jsdom.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 */
  24. const fs = require("fs");
  25. const crypto = require("crypto");
  26. const { JSDOM, VirtualConsole } = require("jsdom");
  27. const dataUri = require("strong-data-uri");
  28. const iconv = require("iconv-lite");
  29. const request = require("request-promise-native");
  30. const SCRIPTS = [
  31. "../../lib/index.js",
  32. "../../lib/hooks/content/content-hooks.js",
  33. "../../lib/frame-tree/content/content-frame-tree.js",
  34. "../../lib/single-file/single-file-util.js",
  35. "../../lib/single-file/single-file-helper.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. "../../common/index.js",
  51. "../../common/ui/content/content-infobar.js"
  52. ];
  53. exports.getPageData = async options => {
  54. const pageContent = (await request({
  55. method: "GET",
  56. uri: options.url,
  57. resolveWithFullResponse: true,
  58. encoding: null,
  59. headers: {
  60. "User-Agent": options.userAgent
  61. }
  62. })).body.toString();
  63. const jsdomOptions = {
  64. url: options.url,
  65. virtualConsole: new VirtualConsole(),
  66. userAgent: options.userAgent,
  67. pretendToBeVisual: true,
  68. runScripts: "outside-only",
  69. resources: "usable"
  70. };
  71. if (options.browserWidth && options.browserHeight) {
  72. jsdomOptions.beforeParse = function (window) {
  73. window.outerWidth = window.innerWidth = options.browserWidth;
  74. window.outerHeight = window.innerHeight = options.browserHeight;
  75. };
  76. }
  77. let dom;
  78. try {
  79. dom = new JSDOM(pageContent, jsdomOptions);
  80. options.insertSingleFileComment = true;
  81. options.insertFaviconLink = true;
  82. const win = dom.window;
  83. const doc = win.document;
  84. let scripts = (await Promise.all(SCRIPTS.concat(options.browserScripts).map(scriptPath => fs.readFileSync(require.resolve(scriptPath)).toString()))).join("\n");
  85. const fileContents = {
  86. "/lib/hooks/content/content-hooks-web.js": fs.readFileSync(require.resolve("../../lib/hooks/content/content-hooks-web.js")).toString(),
  87. "/lib/hooks/content/content-hooks-frames-web.js": fs.readFileSync(require.resolve("../../lib/hooks/content/content-hooks-frames-web.js")).toString(),
  88. "/common/ui/content/content-infobar-web.js": fs.readFileSync(require.resolve("../../common/ui/content/content-infobar-web.js")).toString()
  89. };
  90. scripts = scripts + ";this.singlefile.lib.getFileContent = filename => (" + JSON.stringify(fileContents) + ")[filename];";
  91. dom.window.eval(scripts);
  92. if (dom.window.document.readyState == "loading") {
  93. await new Promise(resolve => win.document.onload = resolve);
  94. }
  95. win.Element.prototype.getBoundingClientRect = undefined;
  96. executeFrameScripts(doc, scripts);
  97. if (!options.saveRawPage && !options.removeFrames) {
  98. options.frames = await win.singlefile.lib.frameTree.content.frames.getAsync(options);
  99. }
  100. options.win = win;
  101. options.doc = doc;
  102. options.removeHiddenElements = false;
  103. const SingleFile = getSingleFileClass(win);
  104. const singleFile = new SingleFile(options);
  105. await singleFile.run();
  106. const pageData = await singleFile.getPageData();
  107. if (options.includeInfobar) {
  108. await win.singlefile.common.ui.content.infobar.includeScript(pageData);
  109. }
  110. return pageData;
  111. } finally {
  112. if (dom && dom.window) {
  113. dom.window.close();
  114. }
  115. }
  116. };
  117. function executeFrameScripts(doc, scripts) {
  118. const frameElements = doc.querySelectorAll("iframe, frame");
  119. frameElements.forEach(frameElement => {
  120. try {
  121. frameElement.contentWindow.Element.prototype.getBoundingClientRect = undefined;
  122. frameElement.contentWindow.eval(scripts);
  123. executeFrameScripts(frameElement.contentDocument, scripts);
  124. } catch (error) {
  125. // ignored
  126. }
  127. });
  128. }
  129. function getSingleFileClass(win) {
  130. const helper = win.singlefile.lib.helper;
  131. const modules = {
  132. helper: helper,
  133. srcsetParser: win.singlefile.lib.vendor.srcsetParser,
  134. cssMinifier: win.singlefile.lib.vendor.cssMinifier,
  135. htmlMinifier: win.singlefile.lib.modules.htmlMinifier,
  136. serializer: win.singlefile.lib.modules.serializer,
  137. fontsMinifier: win.singlefile.lib.modules.fontsMinifier,
  138. fontsAltMinifier: win.singlefile.lib.modules.fontsAltMinifier,
  139. cssRulesMinifier: win.singlefile.lib.modules.cssRulesMinifier,
  140. matchedRules: win.singlefile.lib.modules.matchedRules,
  141. mediasAltMinifier: win.singlefile.lib.modules.mediasAltMinifier,
  142. imagesAltMinifier: win.singlefile.lib.modules.imagesAltMinifier
  143. };
  144. const domUtil = {
  145. getResourceContent,
  146. digestText
  147. };
  148. return win.singlefile.lib.core.getClass(win.singlefile.lib.util.getInstance(modules, domUtil), win.singlefile.lib.vendor.cssTree);
  149. }
  150. async function digestText(algo, text) {
  151. const hash = crypto.createHash(algo.replace("-", "").toLowerCase());
  152. hash.update(text, "utf-8");
  153. return hash.digest("hex");
  154. }
  155. async function getResourceContent(resourceURL, options) {
  156. const resourceContent = await request({
  157. method: "GET",
  158. uri: resourceURL,
  159. resolveWithFullResponse: true,
  160. encoding: null,
  161. headers: {
  162. "User-Agent": options.userAgent
  163. }
  164. });
  165. return {
  166. getUrl() {
  167. return resourceContent.request.href;
  168. },
  169. getContentType() {
  170. return resourceContent.headers["content-type"];
  171. },
  172. getStatusCode() {
  173. return resourceContent.statusCode;
  174. },
  175. getSize() {
  176. return resourceContent.body.byteLength;
  177. },
  178. getText(charset) {
  179. return iconv.decode(resourceContent.body, charset);
  180. },
  181. async getDataUri(contentType) {
  182. return dataUri.encode(resourceContent.body, contentType || this.getContentType());
  183. }
  184. };
  185. }