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