frame-tree.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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.imageData = messageFrameData.imageData;
  87. frameData.postersData = messageFrameData.postersData;
  88. frameData.canvasData = messageFrameData.canvasData;
  89. frameData.fontsData = messageFrameData.fontsData;
  90. frameData.processed = messageFrameData.processed;
  91. frameData.timeout = messageFrameData.timeout;
  92. });
  93. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  94. if (!remainingFrames) {
  95. sessions.delete(message.sessionId);
  96. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  97. if (windowData.resolve) {
  98. windowData.resolve(windowData.frames);
  99. }
  100. }
  101. }
  102. }
  103. function processFrames(frameElements, options, parentWindowId, sessionId) {
  104. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  105. if (frameElements.length) {
  106. processFramesSync(frameElements, options, parentWindowId, sessionId);
  107. }
  108. }
  109. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  110. const framesData = [];
  111. frameElements.forEach((frameElement, frameIndex) => {
  112. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  113. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), windowId);
  114. framesData.push({ windowId });
  115. if (!frameElement.contentDocument) {
  116. try {
  117. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  118. } catch (error) {
  119. /* ignored */
  120. }
  121. }
  122. timeout.set(() => sendInitResponse({ framesData: [{ windowId, processed: true, timeout: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  123. });
  124. sendInitResponse({ framesData, sessionId });
  125. }
  126. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  127. const framesData = [];
  128. frameElements.forEach((frameElement, frameIndex) => {
  129. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  130. const frameDoc = frameElement.contentDocument;
  131. if (frameDoc) {
  132. try {
  133. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  134. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  135. } catch (error) {
  136. framesData.push({ windowId, processed: true });
  137. }
  138. }
  139. });
  140. sendInitResponse({ framesData, sessionId });
  141. }
  142. function sendInitResponse(message) {
  143. message.method = INIT_RESPONSE_MESSAGE;
  144. try {
  145. top.frameTree.initResponse(message);
  146. } catch (error) {
  147. sendMessage(top, message, true);
  148. }
  149. }
  150. function sendMessage(targetWindow, message, useChannel) {
  151. if (useChannel) {
  152. const channel = new MessageChannel();
  153. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  154. channel.port1.postMessage(message);
  155. } else {
  156. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  157. }
  158. }
  159. function getFrameData(document, window, windowId, options) {
  160. const docData = docHelper.preProcessDoc(document, window, options);
  161. const content = docHelper.serialize(document);
  162. docHelper.postProcessDoc(document, window, options);
  163. const baseURI = document.baseURI.split("#")[0];
  164. return {
  165. windowId,
  166. content,
  167. baseURI,
  168. title: document.title,
  169. stylesheetContents: docData.stylesheetContents,
  170. imageData: docData.imageData,
  171. postersData: docData.postersData,
  172. canvasData: docData.canvasData,
  173. fontsData: docData.fontsData,
  174. processed: true
  175. };
  176. }
  177. })();