frame-tree.js 6.6 KB

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