frame-tree.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 window, top, document, addEventListener, docHelper, timeout, MessageChannel, superFetch, fetch, TextDecoder, DOMParser, lazyLoader, setTimeout */
  21. this.frameTree = this.frameTree || (() => {
  22. const MESSAGE_PREFIX = "__frameTree__::";
  23. const FRAMES_CSS_SELECTOR = "iframe, frame, object[type=\"text/html\"][data]";
  24. const INIT_REQUEST_MESSAGE = "initRequest";
  25. const INIT_RESPONSE_MESSAGE = "initResponse";
  26. const TARGET_ORIGIN = "*";
  27. const TIMEOUT_INIT_REQUEST_MESSAGE = 750;
  28. const PREFIX_VALID_FRAME_URL = /^https?:\/\//;
  29. const TOP_WINDOW_ID = "0";
  30. const WINDOW_ID_SEPARATOR = ".";
  31. const TOP_WINDOW = window == top;
  32. const sessions = new Map();
  33. let windowId;
  34. if (TOP_WINDOW) {
  35. windowId = TOP_WINDOW_ID;
  36. }
  37. addEventListener("message", event => {
  38. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  39. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  40. if (!TOP_WINDOW && message.method == INIT_REQUEST_MESSAGE) {
  41. window.stop();
  42. initRequest(message);
  43. if (message.options.loadDeferredImages && window.lazyLoader) {
  44. lazyLoader.process(message.options);
  45. }
  46. } else if (message.method == INIT_RESPONSE_MESSAGE) {
  47. const port = event.ports[0];
  48. port.onmessage = event => initResponse(event.data);
  49. }
  50. event.preventDefault();
  51. event.stopPropagation();
  52. }
  53. }, true);
  54. return {
  55. getAsync: async options => {
  56. const sessionId = options.sessionId;
  57. options = JSON.parse(JSON.stringify(options));
  58. return new Promise(resolve => {
  59. sessions.set(sessionId, { frames: [], resolve });
  60. initRequest({ windowId, sessionId, options });
  61. });
  62. },
  63. getSync: options => {
  64. const sessionId = options.sessionId;
  65. options = JSON.parse(JSON.stringify(options));
  66. sessions.set(sessionId, { frames: [] });
  67. initRequest({ windowId, sessionId, options });
  68. return sessions.get(sessionId).frames;
  69. },
  70. initResponse,
  71. TIMEOUT_INIT_REQUEST_MESSAGE
  72. };
  73. function initRequest(message) {
  74. const sessionId = message.sessionId;
  75. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  76. if (!TOP_WINDOW) {
  77. windowId = message.windowId;
  78. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId });
  79. }
  80. processFrames(frameElements, message.options, windowId, sessionId);
  81. }
  82. function initResponse(message) {
  83. const windowData = sessions.get(message.sessionId);
  84. if (windowData) {
  85. message.framesData.forEach(messageFrameData => {
  86. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  87. if (!frameData) {
  88. frameData = { windowId: messageFrameData.windowId };
  89. windowData.frames.push(frameData);
  90. }
  91. if (!frameData.processed) {
  92. frameData.content = messageFrameData.content;
  93. frameData.baseURI = messageFrameData.baseURI;
  94. frameData.title = messageFrameData.title;
  95. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  96. frameData.imageData = messageFrameData.imageData;
  97. frameData.postersData = messageFrameData.postersData;
  98. frameData.canvasData = messageFrameData.canvasData;
  99. frameData.fontsData = messageFrameData.fontsData;
  100. frameData.usedFonts = messageFrameData.usedFonts;
  101. frameData.shadowRootContents = messageFrameData.shadowRootContents;
  102. frameData.processed = messageFrameData.processed;
  103. frameData.timeout = messageFrameData.timeout;
  104. }
  105. });
  106. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  107. if (!remainingFrames) {
  108. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  109. if (windowData.resolve) {
  110. windowData.resolve(windowData.frames);
  111. sessions.delete(message.sessionId);
  112. }
  113. }
  114. }
  115. }
  116. function processFrames(frameElements, options, parentWindowId, sessionId) {
  117. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  118. if (frameElements.length) {
  119. processFramesSync(frameElements, options, parentWindowId, sessionId);
  120. }
  121. }
  122. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  123. const framesData = [];
  124. frameElements.forEach((frameElement, frameIndex) => {
  125. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  126. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  127. framesData.push({ windowId });
  128. try {
  129. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  130. } catch (error) {
  131. /* ignored */
  132. }
  133. setTimeout(async () => {
  134. let frameDoc;
  135. if (frameElement.src && frameElement.src.match(PREFIX_VALID_FRAME_URL)) {
  136. frameDoc = await getFrameDoc(frameElement.src, parentWindowId, options);
  137. }
  138. if (frameDoc) {
  139. sendInitResponse({ framesData: [getFrameData(frameDoc, null, windowId, options)] });
  140. timeout.set(() => sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId }));
  141. } else {
  142. sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId });
  143. }
  144. }, TIMEOUT_INIT_REQUEST_MESSAGE);
  145. });
  146. sendInitResponse({ framesData, sessionId });
  147. }
  148. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  149. const framesData = [];
  150. frameElements.forEach((frameElement, frameIndex) => {
  151. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  152. let frameDoc;
  153. try {
  154. frameDoc = frameElement.contentDocument;
  155. } catch (error) {
  156. // ignored
  157. }
  158. if (frameDoc) {
  159. try {
  160. frameElement.contentWindow.stop();
  161. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  162. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  163. } catch (error) {
  164. framesData.push({ windowId, processed: true });
  165. }
  166. }
  167. });
  168. sendInitResponse({ framesData, sessionId });
  169. }
  170. function sendInitResponse(message) {
  171. message.method = INIT_RESPONSE_MESSAGE;
  172. try {
  173. top.frameTree.initResponse(message);
  174. } catch (error) {
  175. sendMessage(top, message, true);
  176. }
  177. }
  178. function sendMessage(targetWindow, message, useChannel) {
  179. if (useChannel) {
  180. const channel = new MessageChannel();
  181. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  182. channel.port1.postMessage(message);
  183. } else {
  184. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  185. }
  186. }
  187. async function getFrameDoc(frameUrl, parentWindowId, options) {
  188. let frameContent;
  189. try {
  190. frameContent = await ((typeof superFetch !== "undefined" && superFetch.fetch) || fetch)(frameUrl);
  191. } catch (error) {
  192. /* ignored */
  193. }
  194. if (frameContent && frameContent.status >= 400 && superFetch.hostFetch) {
  195. try {
  196. frameContent = await superFetch.hostFetch(frameUrl);
  197. } catch (error) {
  198. /* ignored */
  199. }
  200. }
  201. if (frameContent) {
  202. const contentType = frameContent.headers && frameContent.headers.get("content-type");
  203. let charset, mimeType;
  204. if (contentType) {
  205. const matchContentType = contentType.toLowerCase().split(";");
  206. mimeType = matchContentType[0].trim();
  207. if (!mimeType.includes("/")) {
  208. mimeType = "text/html";
  209. }
  210. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  211. if (charsetValue) {
  212. const matchCharset = charsetValue.match(/^charset=(.*)/);
  213. if (matchCharset) {
  214. charset = docHelper.removeQuotes(matchCharset[1]);
  215. }
  216. }
  217. }
  218. let doc;
  219. try {
  220. const buffer = await frameContent.arrayBuffer();
  221. const content = (new TextDecoder(charset)).decode(buffer);
  222. const domParser = new DOMParser();
  223. doc = domParser.parseFromString(content, mimeType);
  224. } catch (error) {
  225. /* ignored */
  226. }
  227. if (doc) {
  228. const frameElements = doc.documentElement.querySelectorAll(FRAMES_CSS_SELECTOR);
  229. frameElements.forEach((frameElement, frameIndex) => {
  230. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  231. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  232. });
  233. return doc;
  234. }
  235. }
  236. }
  237. function getFrameData(document, window, windowId, options) {
  238. const docData = docHelper.preProcessDoc(document, window, options);
  239. const content = docHelper.serialize(document);
  240. docHelper.postProcessDoc(document, options);
  241. const baseURI = document.baseURI.split("#")[0];
  242. return {
  243. windowId,
  244. content,
  245. baseURI,
  246. title: document.title,
  247. stylesheetContents: docData.stylesheetContents,
  248. imageData: docData.imageData,
  249. postersData: docData.postersData,
  250. canvasData: docData.canvasData,
  251. fontsData: docData.fontsData,
  252. usedFonts: docData.usedFonts,
  253. shadowRootContents: docData.shadowRootContents,
  254. processed: true
  255. };
  256. }
  257. })();