frame-tree.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 */
  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 TOP_WINDOW_ID = "0";
  29. const WINDOW_ID_SEPARATOR = ".";
  30. const TOP_WINDOW = window == top;
  31. let sessions = new Map(), windowId;
  32. if (TOP_WINDOW) {
  33. windowId = TOP_WINDOW_ID;
  34. }
  35. addEventListener("message", event => {
  36. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  37. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  38. if (message.method == INIT_REQUEST_MESSAGE) {
  39. initRequest(message);
  40. } else if (message.method == INIT_RESPONSE_MESSAGE) {
  41. const port = event.ports[0];
  42. port.onmessage = event => initResponse(event.data);
  43. }
  44. }
  45. }, false);
  46. return {
  47. getAsync: async options => {
  48. const sessionId = options.sessionId;
  49. options = JSON.parse(JSON.stringify(options));
  50. return new Promise(resolve => {
  51. sessions.set(sessionId, { frames: [], resolve });
  52. initRequest({ windowId, sessionId, options });
  53. });
  54. },
  55. getSync: options => {
  56. const sessionId = options.sessionId;
  57. options = JSON.parse(JSON.stringify(options));
  58. sessions.set(sessionId, { frames: [] });
  59. initRequest({ windowId, sessionId, options });
  60. return sessions.get(sessionId).frames;
  61. },
  62. initResponse
  63. };
  64. function initRequest(message) {
  65. const sessionId = message.sessionId;
  66. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  67. if (!TOP_WINDOW) {
  68. windowId = message.windowId;
  69. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId });
  70. }
  71. processFrames(frameElements, message.options, windowId, sessionId);
  72. }
  73. function initResponse(message) {
  74. const windowData = sessions.get(message.sessionId);
  75. if (windowData) {
  76. message.framesData.forEach(messageFrameData => {
  77. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  78. if (!frameData) {
  79. frameData = { windowId: messageFrameData.windowId };
  80. windowData.frames.push(frameData);
  81. }
  82. frameData.content = messageFrameData.content;
  83. frameData.baseURI = messageFrameData.baseURI;
  84. frameData.title = messageFrameData.title;
  85. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  86. frameData.responsiveImageData = messageFrameData.responsiveImageData;
  87. frameData.imageData = messageFrameData.imageData;
  88. frameData.postersData = messageFrameData.postersData;
  89. frameData.canvasData = messageFrameData.canvasData;
  90. frameData.fontsData = messageFrameData.fontsData;
  91. frameData.processed = messageFrameData.processed;
  92. frameData.timeout = messageFrameData.timeout;
  93. });
  94. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  95. if (!remainingFrames) {
  96. sessions.delete(message.sessionId);
  97. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  98. if (windowData.resolve) {
  99. windowData.resolve(windowData.frames);
  100. }
  101. }
  102. }
  103. }
  104. function processFrames(frameElements, options, parentWindowId, sessionId) {
  105. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  106. if (frameElements.length) {
  107. processFramesSync(frameElements, options, parentWindowId, sessionId);
  108. }
  109. }
  110. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  111. const framesData = [];
  112. frameElements.forEach((frameElement, frameIndex) => {
  113. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  114. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  115. framesData.push({ windowId });
  116. if (!frameElement.contentDocument) {
  117. try {
  118. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  119. } catch (error) {
  120. /* ignored */
  121. }
  122. }
  123. timeout.set(() => sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  124. });
  125. sendInitResponse({ framesData, sessionId });
  126. }
  127. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  128. const framesData = [];
  129. frameElements.forEach((frameElement, frameIndex) => {
  130. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  131. const frameDoc = frameElement.contentDocument;
  132. if (frameDoc) {
  133. try {
  134. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  135. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  136. } catch (error) {
  137. framesData.push({ windowId, processed: true });
  138. }
  139. }
  140. });
  141. sendInitResponse({ framesData, sessionId });
  142. }
  143. function sendInitResponse(message) {
  144. message.method = INIT_RESPONSE_MESSAGE;
  145. try {
  146. top.frameTree.initResponse(message);
  147. } catch (error) {
  148. sendMessage(top, message, true);
  149. }
  150. }
  151. function sendMessage(targetWindow, message, useChannel) {
  152. if (useChannel) {
  153. const channel = new MessageChannel();
  154. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  155. channel.port1.postMessage(message);
  156. } else {
  157. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  158. }
  159. }
  160. function getFrameData(document, window, windowId, options) {
  161. const docData = docHelper.preProcessDoc(document, window, options);
  162. const content = docHelper.serialize(document);
  163. docHelper.postProcessDoc(document, window, options);
  164. const baseURI = document.baseURI.split("#")[0];
  165. return {
  166. windowId,
  167. content,
  168. baseURI,
  169. title: document.title,
  170. stylesheetContents: docData.stylesheetContents,
  171. responsiveImageData: docData.responsiveImageData,
  172. imageData: docData.imageData,
  173. postersData: docData.postersData,
  174. canvasData: docData.canvasData,
  175. fontsData: docData.fontsData,
  176. processed: true
  177. };
  178. }
  179. })();