doc-helper.js 17 KB

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