frame-tree.js 9.4 KB

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