frame-tree.js 9.3 KB

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