frame-tree.js 9.5 KB

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