frame-tree.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 */
  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 = isTopWindow(window);
  28. let sessions, windowId;
  29. if (TOP_WINDOW) {
  30. sessions = new Map();
  31. windowId = "0";
  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. initResponse(message);
  40. }
  41. }
  42. }, false);
  43. return {
  44. getAsync: async options => {
  45. const sessionId = options.sessionId;
  46. options = JSON.parse(JSON.stringify(options));
  47. return new Promise(resolve => {
  48. sessions.set(sessionId, { frames: [], resolve });
  49. initRequest({ windowId, sessionId, options });
  50. });
  51. },
  52. getSync: options => {
  53. const sessionId = options.sessionId;
  54. options = JSON.parse(JSON.stringify(options));
  55. sessions.set(sessionId, { frames: [] });
  56. initRequest({ windowId, sessionId, options });
  57. return sessions.get(sessionId);
  58. },
  59. initResponse
  60. };
  61. function initRequest(message) {
  62. const sessionId = message.sessionId;
  63. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  64. if (!TOP_WINDOW) {
  65. windowId = message.windowId;
  66. const docData = docHelper.preProcessDoc(document, window, message.options);
  67. const content = docHelper.serialize(document);
  68. docHelper.postProcessDoc(document, window, message.options);
  69. callTopInitResponse({
  70. method: INIT_RESPONSE_MESSAGE, framesData: [{
  71. windowId,
  72. content,
  73. baseURI: document.baseURI,
  74. title: document.title,
  75. emptyStyleRulesText: docData.emptyStyleRulesText,
  76. canvasData: docData.canvasData,
  77. processed: true,
  78. }], sessionId
  79. });
  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.emptyStyleRulesText = messageFrameData.emptyStyleRulesText;
  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.resolve(windowData.frames.sort((frame1, frame2) => frame2.windowId.split(".").length - frame1.windowId.split(".").length));
  104. }
  105. }
  106. }
  107. function processFrames(frameElements, options, windowId, sessionId) {
  108. let framesData = [];
  109. frameElements.forEach((frameElement, frameIndex) => {
  110. const frameWindowId = windowId + "." + frameIndex;
  111. frameElement.setAttribute(docHelper.windowIdAttributeName(options.sessionId), frameWindowId);
  112. framesData.push({ windowId: frameWindowId });
  113. if (!frameElement.contentDocument) {
  114. try {
  115. frameElement.contentWindow.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: INIT_REQUEST_MESSAGE, windowId: frameWindowId, sessionId, options }), "*");
  116. } catch (error) {
  117. /* ignored */
  118. }
  119. }
  120. timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({
  121. method: INIT_RESPONSE_MESSAGE,
  122. framesData: [{ windowId: frameWindowId, processed: true, timeout: true }],
  123. windowId: frameWindowId, sessionId
  124. }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
  125. });
  126. callTopInitResponse({ method: INIT_RESPONSE_MESSAGE, framesData, windowId, sessionId });
  127. if (frameElements.length) {
  128. framesData = [];
  129. frameElements.forEach((frameElement, frameIndex) => {
  130. const frameWindowId = windowId + "." + frameIndex;
  131. const frameWindow = frameElement.contentWindow;
  132. const frameDoc = frameElement.contentDocument;
  133. if (frameDoc) {
  134. try {
  135. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, frameWindowId, sessionId);
  136. const docData = docHelper.preProcessDoc(frameDoc, frameWindow, options);
  137. framesData.push({
  138. windowId: frameWindowId,
  139. content: docHelper.serialize(frameDoc),
  140. baseURI: frameDoc.baseURI,
  141. title: frameDoc.title,
  142. emptyStyleRulesText: docData.emptyStyleRulesText,
  143. canvasData: docData.canvasData,
  144. processed: true
  145. });
  146. docHelper.postProcessDoc(frameDoc, frameWindow, options);
  147. } catch (error) {
  148. framesData.push({
  149. windowId: frameWindowId,
  150. processed: true
  151. });
  152. }
  153. }
  154. });
  155. callTopInitResponse({ method: INIT_RESPONSE_MESSAGE, framesData, windowId, sessionId });
  156. }
  157. }
  158. function callTopInitResponse(message) {
  159. try {
  160. top.frameTree.initResponse(message);
  161. } catch (error) {
  162. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify(message), "*");
  163. }
  164. }
  165. function isTopWindow(win) {
  166. return win == top;
  167. }
  168. })();