doc-helper.js 16 KB

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