frame-tree.js 6.6 KB

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