frame-tree.js 9.7 KB

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