doc-helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global hooksFrame */
  21. this.docHelper = this.docHelper || (() => {
  22. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  23. const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-single-file-preserved-space-element";
  24. const SHADOW_ROOT_ATTRIBUTE_NAME = "data-single-file-shadow-root-element";
  25. const WIN_ID_ATTRIBUTE_NAME = "data-frame-tree-win-id";
  26. const IMAGE_ATTRIBUTE_NAME = "data-single-file-image";
  27. const INPUT_VALUE_ATTRIBUTE_NAME = "data-single-file-value";
  28. const LAZY_SRC_ATTRIBUTE_NAME = "data-lazy-loaded-src";
  29. const IGNORED_REMOVED_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT"];
  30. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  31. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  32. const FONT_WEIGHTS = {
  33. normal: "400",
  34. bold: "700"
  35. };
  36. return {
  37. preProcessDoc,
  38. postProcessDoc,
  39. serialize,
  40. removeQuotes,
  41. WIN_ID_ATTRIBUTE_NAME,
  42. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  43. REMOVED_CONTENT_ATTRIBUTE_NAME,
  44. IMAGE_ATTRIBUTE_NAME,
  45. INPUT_VALUE_ATTRIBUTE_NAME,
  46. SHADOW_ROOT_ATTRIBUTE_NAME
  47. };
  48. function preProcessDoc(doc, win, options) {
  49. doc.querySelectorAll("script").forEach(element => element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>"));
  50. doc.querySelectorAll("noscript").forEach(element => {
  51. const disabledNoscriptElement = doc.createElement("disabled-noscript");
  52. Array.from(element.childNodes).forEach(node => disabledNoscriptElement.appendChild(node));
  53. disabledNoscriptElement.hidden = true;
  54. element.parentElement.replaceChild(disabledNoscriptElement, element);
  55. });
  56. if (doc.head) {
  57. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.hidden = true);
  58. }
  59. let canvasData, imageData, usedFonts, shadowRootContents;
  60. if (win) {
  61. canvasData = getCanvasData(doc, win);
  62. imageData = getImageData(doc, win, options);
  63. if (doc.body && (options.removeHiddenElements || options.removeUnusedFonts || options.compressHTML)) {
  64. let elementsInfo = getElementsInfo(win, doc.body);
  65. if (options.removeHiddenElements) {
  66. const markerRemovedContent = REMOVED_CONTENT_ATTRIBUTE_NAME;
  67. let ignoredTags = JSON.parse(JSON.stringify(IGNORED_REMOVED_TAG_NAMES));
  68. if (!options.removeScripts) {
  69. ignoredTags = ignoredTags.concat("SCRIPT");
  70. }
  71. markHiddenCandidates(win, doc.body, elementsInfo, false, markerRemovedContent, new Set(), ignoredTags);
  72. markHiddenElements(win, doc.body, markerRemovedContent);
  73. doc.querySelectorAll("iframe").forEach(element => {
  74. if (element.getBoundingClientRect) {
  75. const boundingRect = element.getBoundingClientRect();
  76. if (element.hidden || element.style.display == "none" || boundingRect.width <= 1 && boundingRect.height <= 1) {
  77. element.setAttribute(markerRemovedContent, "");
  78. }
  79. }
  80. });
  81. elementsInfo = new Map(Array.from(elementsInfo).filter(([element]) => element.getAttribute(markerRemovedContent) != ""));
  82. }
  83. if (options.removeUnusedFonts) {
  84. let loadedFonts;
  85. if (doc.fonts) {
  86. loadedFonts = Array.from(doc.fonts).filter(font => font.status == "loaded" || font.status == "loading");
  87. }
  88. usedFonts = getUsedFonts(elementsInfo, loadedFonts);
  89. }
  90. if (options.compressHTML) {
  91. elementsInfo.forEach((elementInfo, element) => {
  92. if (elementInfo.whiteSpace.startsWith("pre")) {
  93. element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
  94. }
  95. });
  96. }
  97. elementsInfo.forEach((elementInfo, element) => {
  98. let elementIndex = 0;
  99. if (elementInfo.shadowRoot) {
  100. element.setAttribute(SHADOW_ROOT_ATTRIBUTE_NAME, elementIndex);
  101. elementIndex++;
  102. if (!shadowRootContents) {
  103. shadowRootContents = [];
  104. }
  105. shadowRootContents.push({ content: element.shadowRoot.innerHTML, height: element.clientHeight });
  106. }
  107. });
  108. }
  109. }
  110. retrieveInputValues(doc);
  111. return {
  112. canvasData,
  113. fontsData: getFontsData(doc),
  114. stylesheetContents: getStylesheetContents(doc),
  115. imageData,
  116. postersData: getPostersData(doc),
  117. usedFonts,
  118. shadowRootContents,
  119. referrer: doc.referrer
  120. };
  121. }
  122. function getUsedFonts(styles, loadedFonts) {
  123. const usedFonts = new Set();
  124. styles.forEach(style => {
  125. const fontFamilyNames = style.fontFamily.split(",");
  126. fontFamilyNames.forEach(fontFamilyName => {
  127. fontFamilyName = normalizeFontFamily(fontFamilyName);
  128. if (!loadedFonts || loadedFonts.find(font => normalizeFontFamily(font.family) == fontFamilyName && font.style == style.fontStyle)) {
  129. const { fontWeight, fontStyle, fontVariant } = style;
  130. usedFonts.add([fontFamilyName, fontWeight, fontStyle, fontVariant]);
  131. }
  132. });
  133. });
  134. return Array.from(usedFonts);
  135. }
  136. function normalizeFontFamily(fontFamilyName) {
  137. return removeQuotes(fontFamilyName.trim()).toLowerCase();
  138. }
  139. function getElementsInfo(win, element, elementsInfo = new Map()) {
  140. const elements = Array.from(element.childNodes).filter(node => !win || node instanceof win.Element);
  141. elements.forEach(element => {
  142. getElementsInfo(win, element, elementsInfo);
  143. const computedStyle = win.getComputedStyle(element);
  144. elementsInfo.set(element, {
  145. display: computedStyle.getPropertyValue("display"),
  146. opacity: computedStyle.getPropertyValue("opacity"),
  147. visibility: computedStyle.getPropertyValue("visibility"),
  148. fontFamily: computedStyle.getPropertyValue("font-family"),
  149. fontWeight: getFontWeight(computedStyle.getPropertyValue("font-weight")),
  150. fontStyle: computedStyle.getPropertyValue("font-style") || "normal",
  151. fontVariant: computedStyle.getPropertyValue("font-variant") || "normal",
  152. whiteSpace: computedStyle.getPropertyValue("white-space"),
  153. shadowRoot: element.shadowRoot
  154. });
  155. });
  156. return elementsInfo;
  157. }
  158. function markHiddenCandidates(win, element, styles, elementHidden, markerRemovedContent, removedCandidates, ignoredTags) {
  159. const elements = Array.from(element.childNodes).filter(node => node instanceof win.HTMLElement);
  160. elements.forEach(element => markHiddenCandidates(win, element, styles, elementHidden || testHiddenElement(element, styles.get(element)), markerRemovedContent, removedCandidates, ignoredTags));
  161. if (elementHidden && !ignoredTags.includes(element.tagName)) {
  162. if (elements.length) {
  163. if (!elements.find(element => !removedCandidates.has(element))) {
  164. removedCandidates.add(element);
  165. elements.forEach(element => element.setAttribute(markerRemovedContent, ""));
  166. }
  167. } else {
  168. removedCandidates.add(element);
  169. }
  170. }
  171. }
  172. function markHiddenElements(win, element, markerRemovedContent) {
  173. const elements = Array.from(element.childNodes).filter(node => node.nodeType == win.Node.ELEMENT_NODE);
  174. if (element.getAttribute(markerRemovedContent) == "") {
  175. element.removeAttribute(markerRemovedContent);
  176. } else {
  177. elements.forEach(element => markHiddenElements(win, element, markerRemovedContent));
  178. }
  179. }
  180. function testHiddenElement(element, style) {
  181. let hidden = false;
  182. if (style) {
  183. hidden = style.display == "none";
  184. if (!hidden && (style.opacity == "0" || style.visibility == "hidden") && element.getBoundingClientRect) {
  185. const boundingRect = element.getBoundingClientRect();
  186. hidden = !boundingRect.width && !boundingRect.height;
  187. }
  188. }
  189. return Boolean(hidden);
  190. }
  191. function postProcessDoc(doc, options) {
  192. doc.querySelectorAll("disabled-noscript").forEach(element => {
  193. const noscriptElement = doc.createElement("noscript");
  194. Array.from(element.childNodes).forEach(node => noscriptElement.appendChild(node));
  195. element.parentElement.replaceChild(noscriptElement, element);
  196. });
  197. if (doc.head) {
  198. doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
  199. }
  200. if (options.removeHiddenElements) {
  201. doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME));
  202. }
  203. if (options.compressHTML) {
  204. doc.querySelectorAll("[" + PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME));
  205. }
  206. doc.querySelectorAll("[" + IMAGE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(IMAGE_ATTRIBUTE_NAME));
  207. doc.querySelectorAll("[" + INPUT_VALUE_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME));
  208. doc.querySelectorAll("[" + SHADOW_ROOT_ATTRIBUTE_NAME + "]").forEach(element => element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME));
  209. }
  210. function getCanvasData(doc, win) {
  211. if (doc) {
  212. const canvasData = [];
  213. doc.querySelectorAll("canvas").forEach(canvasElement => {
  214. try {
  215. const size = getSize(win, canvasElement);
  216. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: size.width, height: size.height });
  217. } catch (error) {
  218. canvasData.push(null);
  219. }
  220. });
  221. return canvasData;
  222. }
  223. }
  224. function getStylesheetContents(doc) {
  225. if (doc) {
  226. const contents = [];
  227. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  228. let stylesheet;
  229. try {
  230. const tempStyleElement = doc.createElement("style");
  231. tempStyleElement.textContent = styleElement.textContent;
  232. doc.body.appendChild(tempStyleElement);
  233. stylesheet = tempStyleElement.sheet;
  234. tempStyleElement.remove();
  235. if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
  236. contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
  237. }
  238. } catch (error) {
  239. /* ignored */
  240. }
  241. });
  242. return contents;
  243. }
  244. }
  245. function getImageData(doc, win, options) {
  246. if (doc) {
  247. const data = [];
  248. doc.querySelectorAll("img").forEach((imageElement, imageElementIndex) => {
  249. imageElement.setAttribute(IMAGE_ATTRIBUTE_NAME, imageElementIndex);
  250. const imageData = {
  251. currentSrc: (options.loadDeferredImages && imageElement.getAttribute(LAZY_SRC_ATTRIBUTE_NAME)) || imageElement.currentSrc
  252. };
  253. imageElement.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
  254. const computedStyle = win.getComputedStyle(imageElement);
  255. if (computedStyle) {
  256. imageData.size = getSize(win, imageElement);
  257. if ((!computedStyle.getPropertyValue("box-shadow") || computedStyle.getPropertyValue("box-shadow") == "none") &&
  258. (!computedStyle.getPropertyValue("background-image") || computedStyle.getPropertyValue("background-image") == "none") &&
  259. (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
  260. imageData.replaceable = true;
  261. imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
  262. imageData.objectFit = computedStyle.getPropertyValue("object-fit");
  263. imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
  264. imageData.objectPosition = computedStyle.getPropertyValue("object-position");
  265. }
  266. }
  267. data.push(imageData);
  268. });
  269. return data;
  270. }
  271. }
  272. function getSize(win, imageElement) {
  273. let pxWidth = imageElement.naturalWidth;
  274. let pxHeight = imageElement.naturalHeight;
  275. if (!pxWidth && !pxHeight) {
  276. const computedStyle = win.getComputedStyle(imageElement);
  277. let removeBorderWidth = false;
  278. if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
  279. const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
  280. const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
  281. const clientWidth = imageElement.clientWidth;
  282. imageElement.style.setProperty("box-sizing", "border-box", "important");
  283. removeBorderWidth = imageElement.clientWidth != clientWidth;
  284. if (boxSizingValue) {
  285. imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
  286. } else {
  287. imageElement.style.removeProperty("box-sizing");
  288. }
  289. }
  290. let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
  291. paddingLeft = getWidth("padding-left", computedStyle);
  292. paddingRight = getWidth("padding-right", computedStyle);
  293. paddingTop = getWidth("padding-top", computedStyle);
  294. paddingBottom = getWidth("padding-bottom", computedStyle);
  295. if (removeBorderWidth) {
  296. borderLeft = getWidth("border-left-width", computedStyle);
  297. borderRight = getWidth("border-right-width", computedStyle);
  298. borderTop = getWidth("border-top-width", computedStyle);
  299. borderBottom = getWidth("border-bottom-width", computedStyle);
  300. } else {
  301. borderLeft = borderRight = borderTop = borderBottom = 0;
  302. }
  303. pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
  304. pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
  305. }
  306. return { pxWidth, pxHeight };
  307. }
  308. function getWidth(styleName, computedStyle) {
  309. if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
  310. return parseFloat(computedStyle.getPropertyValue(styleName));
  311. }
  312. }
  313. function getPostersData(doc) {
  314. if (doc) {
  315. const postersData = [];
  316. doc.querySelectorAll("video").forEach(videoElement => {
  317. if (videoElement.poster) {
  318. postersData.push(null);
  319. } else {
  320. const canvasElement = doc.createElement("canvas");
  321. const context = canvasElement.getContext("2d");
  322. canvasElement.width = videoElement.clientWidth;
  323. canvasElement.height = videoElement.clientHeight;
  324. try {
  325. context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
  326. postersData.push(canvasElement.toDataURL("image/png", ""));
  327. } catch (error) {
  328. postersData.push(null);
  329. }
  330. }
  331. });
  332. return postersData;
  333. }
  334. }
  335. function getFontsData() {
  336. if (typeof hooksFrame != "undefined") {
  337. return hooksFrame.getFontsData();
  338. }
  339. }
  340. function retrieveInputValues(doc) {
  341. doc.querySelectorAll("input").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.value));
  342. doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => input.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, input.checked));
  343. doc.querySelectorAll("textarea").forEach(textarea => textarea.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, textarea.value));
  344. doc.querySelectorAll("select").forEach(select => {
  345. select.querySelectorAll("option").forEach(option => {
  346. if (option.selected) {
  347. option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
  348. }
  349. });
  350. });
  351. }
  352. function serialize(doc) {
  353. const docType = doc.doctype;
  354. let docTypeString = "";
  355. if (docType) {
  356. docTypeString = "<!DOCTYPE " + docType.nodeName;
  357. if (docType.publicId) {
  358. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  359. if (docType.systemId) {
  360. docTypeString += " \"" + docType.systemId + "\"";
  361. }
  362. } else if (docType.systemId) {
  363. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  364. } if (docType.internalSubset) {
  365. docTypeString += " [" + docType.internalSubset + "]";
  366. }
  367. docTypeString += "> ";
  368. }
  369. return docTypeString + doc.documentElement.outerHTML;
  370. }
  371. function removeQuotes(string) {
  372. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  373. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  374. } else {
  375. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  376. }
  377. return string.trim();
  378. }
  379. function getFontWeight(weight) {
  380. return FONT_WEIGHTS[weight] || weight;
  381. }
  382. })();