1
0

frame-tree.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*
  2. * Copyright 2018 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 */
  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.lazyLoadImages && 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. };
  72. function initRequest(message) {
  73. const sessionId = message.sessionId;
  74. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  75. if (!TOP_WINDOW) {
  76. windowId = message.windowId;
  77. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId });
  78. }
  79. processFrames(frameElements, message.options, windowId, sessionId);
  80. }
  81. function initResponse(message) {
  82. const windowData = sessions.get(message.sessionId);
  83. if (windowData) {
  84. message.framesData.forEach(messageFrameData => {
  85. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  86. if (!frameData) {
  87. frameData = { windowId: messageFrameData.windowId };
  88. windowData.frames.push(frameData);
  89. }
  90. if (!frameData.processed) {
  91. frameData.content = messageFrameData.content;
  92. frameData.baseURI = messageFrameData.baseURI;
  93. frameData.title = messageFrameData.title;
  94. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  95. frameData.imageData = messageFrameData.imageData;
  96. frameData.postersData = messageFrameData.postersData;
  97. frameData.canvasData = messageFrameData.canvasData;
  98. frameData.fontsData = messageFrameData.fontsData;
  99. frameData.usedFonts = messageFrameData.usedFonts;
  100. frameData.shadowRootContents = messageFrameData.shadowRootContents;
  101. frameData.processed = messageFrameData.processed;
  102. frameData.timeout = messageFrameData.timeout;
  103. }
  104. });
  105. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  106. if (!remainingFrames) {
  107. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  108. if (windowData.resolve) {
  109. windowData.resolve(windowData.frames);
  110. sessions.delete(message.sessionId);
  111. }
  112. }
  113. }
  114. }
  115. function processFrames(frameElements, options, parentWindowId, sessionId) {
  116. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  117. if (frameElements.length) {
  118. processFramesSync(frameElements, options, parentWindowId, sessionId);
  119. }
  120. }
  121. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  122. const framesData = [];
  123. frameElements.forEach((frameElement, frameIndex) => {
  124. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  125. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  126. framesData.push({ windowId });
  127. try {
  128. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  129. } catch (error) {
  130. /* ignored */
  131. }
  132. timeout.set(async () => {
  133. let frameDoc;
  134. if (frameElement.src && frameElement.src.match(PREFIX_VALID_FRAME_URL)) {
  135. frameDoc = await getFrameDoc(frameElement.src, parentWindowId, options);
  136. }
  137. if (frameDoc) {
  138. sendInitResponse({ framesData: [getFrameData(frameDoc, null, windowId, options)] });
  139. timeout.set(() => sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId }));
  140. } else {
  141. sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId });
  142. }
  143. }, TIMEOUT_INIT_REQUEST_MESSAGE);
  144. });
  145. sendInitResponse({ framesData, sessionId });
  146. }
  147. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  148. const framesData = [];
  149. frameElements.forEach((frameElement, frameIndex) => {
  150. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  151. const frameDoc = frameElement.contentDocument;
  152. if (frameDoc) {
  153. try {
  154. frameElement.contentWindow.stop();
  155. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  156. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  157. } catch (error) {
  158. framesData.push({ windowId, processed: true });
  159. }
  160. }
  161. });
  162. sendInitResponse({ framesData, sessionId });
  163. }
  164. function sendInitResponse(message) {
  165. message.method = INIT_RESPONSE_MESSAGE;
  166. try {
  167. top.frameTree.initResponse(message);
  168. } catch (error) {
  169. sendMessage(top, message, true);
  170. }
  171. }
  172. function sendMessage(targetWindow, message, useChannel) {
  173. if (useChannel) {
  174. const channel = new MessageChannel();
  175. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  176. channel.port1.postMessage(message);
  177. } else {
  178. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  179. }
  180. }
  181. async function getFrameDoc(frameUrl, parentWindowId, options) {
  182. let frameContent;
  183. try {
  184. frameContent = await ((typeof superFetch !== "undefined" && superFetch.fetch) || fetch)(frameUrl);
  185. } catch (error) {
  186. /* ignored */
  187. }
  188. if (frameContent && frameContent.status >= 400 && superFetch.hostFetch) {
  189. try {
  190. frameContent = await superFetch.hostFetch(frameUrl);
  191. } catch (error) {
  192. /* ignored */
  193. }
  194. }
  195. if (frameContent) {
  196. const contentType = frameContent.headers && frameContent.headers.get("content-type");
  197. let charSet, mimeType;
  198. if (contentType) {
  199. const matchContentType = contentType.toLowerCase().split(";");
  200. mimeType = matchContentType[0].trim();
  201. if (mimeType.indexOf("/") <= 0) {
  202. mimeType = "text/html";
  203. }
  204. const charSetValue = matchContentType[1] && matchContentType[1].trim();
  205. if (charSetValue) {
  206. const matchCharSet = charSetValue.match(/^charset=(.*)/);
  207. if (matchCharSet) {
  208. charSet = docHelper.removeQuotes(matchCharSet[1]);
  209. }
  210. }
  211. }
  212. let doc;
  213. try {
  214. const buffer = await frameContent.arrayBuffer();
  215. const content = (new TextDecoder(charSet)).decode(buffer);
  216. const domParser = new DOMParser();
  217. doc = domParser.parseFromString(content, mimeType);
  218. } catch (error) {
  219. /* ignored */
  220. }
  221. if (doc) {
  222. const frameElements = doc.documentElement.querySelectorAll(FRAMES_CSS_SELECTOR);
  223. frameElements.forEach((frameElement, frameIndex) => {
  224. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  225. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  226. });
  227. return doc;
  228. }
  229. }
  230. }
  231. function getFrameData(document, window, windowId, options) {
  232. const docData = docHelper.preProcessDoc(document, window, options);
  233. const content = docHelper.serialize(document);
  234. docHelper.postProcessDoc(document, options);
  235. const baseURI = document.baseURI.split("#")[0];
  236. return {
  237. windowId,
  238. content,
  239. baseURI,
  240. title: document.title,
  241. stylesheetContents: docData.stylesheetContents,
  242. imageData: docData.imageData,
  243. postersData: docData.postersData,
  244. canvasData: docData.canvasData,
  245. fontsData: docData.fontsData,
  246. usedFonts: docData.usedFonts,
  247. shadowRootContents: docData.shadowRootContents,
  248. processed: true
  249. };
  250. }
  251. })();