frame-tree.js 6.4 KB

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