content-frame-tree.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global window, top, document, addEventListener, docHelper, MessageChannel, lazyLoader, browser, setTimeout */
  24. this.frameTree = this.frameTree || (() => {
  25. const MESSAGE_PREFIX = "__frameTree__::";
  26. const FRAMES_CSS_SELECTOR = "iframe, frame, object[type=\"text/html\"][data]";
  27. const INIT_REQUEST_MESSAGE = "initRequest";
  28. const CLEANUP_REQUEST_MESSAGE = "cleanupRequest";
  29. const INIT_RESPONSE_MESSAGE = "frameTree.initResponse";
  30. const TARGET_ORIGIN = "*";
  31. const TIMEOUT_INIT_REQUEST_MESSAGE = 750;
  32. const TOP_WINDOW_ID = "0";
  33. const WINDOW_ID_SEPARATOR = ".";
  34. const TOP_WINDOW = window == top;
  35. const sessions = new Map();
  36. let windowId;
  37. if (TOP_WINDOW) {
  38. windowId = TOP_WINDOW_ID;
  39. if (this.browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
  40. browser.runtime.onMessage.addListener(message => {
  41. if (message.method == INIT_RESPONSE_MESSAGE) {
  42. initResponse(message);
  43. }
  44. });
  45. }
  46. }
  47. addEventListener("message", event => {
  48. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  49. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  50. if (!TOP_WINDOW && message.method == INIT_REQUEST_MESSAGE) {
  51. window.stop();
  52. initRequest(message);
  53. if (message.options.loadDeferredImages && window.lazyLoader) {
  54. lazyLoader.process(message.options);
  55. }
  56. } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
  57. cleanupRequest(message);
  58. } else if (!browser.runtime && message.method == INIT_RESPONSE_MESSAGE) {
  59. const port = event.ports[0];
  60. port.onmessage = event => initResponse(event.data);
  61. }
  62. event.preventDefault();
  63. event.stopPropagation();
  64. }
  65. }, true);
  66. return {
  67. getAsync: async options => {
  68. const sessionId = options.sessionId || 0;
  69. options = JSON.parse(JSON.stringify(options));
  70. return new Promise(resolve => {
  71. sessions.set(sessionId, { frames: [], resolve });
  72. initRequest({ windowId, sessionId, options });
  73. });
  74. },
  75. getSync: options => {
  76. const sessionId = options.sessionId || 0;
  77. options = JSON.parse(JSON.stringify(options));
  78. sessions.set(sessionId, { frames: [] });
  79. initRequest({ windowId, sessionId, options });
  80. return sessions.get(sessionId).frames;
  81. },
  82. cleanup: options => {
  83. const sessionId = options.sessionId || 0;
  84. cleanupRequest({ windowId, sessionId, options: { sessionId } });
  85. },
  86. initResponse,
  87. TIMEOUT_INIT_REQUEST_MESSAGE
  88. };
  89. function initRequest(message) {
  90. const sessionId = message.sessionId;
  91. if (!TOP_WINDOW) {
  92. windowId = message.windowId;
  93. }
  94. processFrames(document, document.querySelectorAll(FRAMES_CSS_SELECTOR), message.options, windowId, sessionId);
  95. if (!TOP_WINDOW) {
  96. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
  97. delete document.documentElement.dataset.requestedFrameId;
  98. }
  99. }
  100. function cleanupRequest(message) {
  101. const sessionId = message.sessionId;
  102. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  103. cleanupFrames(frameElements, message.windowId, sessionId);
  104. }
  105. function initResponse(message) {
  106. const windowData = sessions.get(message.sessionId);
  107. if (windowData) {
  108. if (message.requestedFrameId) {
  109. windowData.requestedFrameId = message.requestedFrameId;
  110. }
  111. message.framesData.forEach(messageFrameData => {
  112. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  113. if (!frameData) {
  114. frameData = { windowId: messageFrameData.windowId };
  115. windowData.frames.push(frameData);
  116. }
  117. if (!frameData.processed) {
  118. frameData.content = messageFrameData.content;
  119. frameData.baseURI = messageFrameData.baseURI;
  120. frameData.title = messageFrameData.title;
  121. frameData.stylesheetsData = messageFrameData.stylesheetsData;
  122. frameData.imageData = messageFrameData.imageData;
  123. frameData.postersData = messageFrameData.postersData;
  124. frameData.canvasData = messageFrameData.canvasData;
  125. frameData.fontsData = messageFrameData.fontsData;
  126. frameData.usedFonts = messageFrameData.usedFonts;
  127. frameData.shadowRootsData = messageFrameData.shadowRootsData;
  128. frameData.processed = messageFrameData.processed;
  129. }
  130. });
  131. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  132. if (!remainingFrames) {
  133. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  134. if (windowData.resolve) {
  135. if (windowData.requestedFrameId) {
  136. windowData.frames.forEach(frameData => {
  137. if (frameData.windowId == windowData.requestedFrameId) {
  138. frameData.requestedFrame = true;
  139. }
  140. });
  141. }
  142. windowData.resolve(windowData.frames);
  143. }
  144. }
  145. }
  146. }
  147. function processFrames(doc, frameElements, options, parentWindowId, sessionId) {
  148. processFramesAsync(doc, frameElements, options, parentWindowId, sessionId);
  149. if (frameElements.length) {
  150. processFramesSync(doc, frameElements, options, parentWindowId, sessionId);
  151. }
  152. }
  153. function processFramesAsync(doc, frameElements, options, parentWindowId, sessionId) {
  154. const framesData = [];
  155. frameElements.forEach((frameElement, frameIndex) => {
  156. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  157. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, windowId);
  158. framesData.push({ windowId });
  159. try {
  160. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  161. } catch (error) {
  162. /* ignored */
  163. }
  164. setTimeout(() => sendInitResponse({ framesData: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  165. });
  166. sendInitResponse({ framesData, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  167. delete doc.documentElement.dataset.requestedFrameId;
  168. }
  169. function processFramesSync(doc, frameElements, options, parentWindowId, sessionId) {
  170. const framesData = [];
  171. frameElements.forEach((frameElement, frameIndex) => {
  172. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  173. let frameDoc;
  174. try {
  175. frameDoc = frameElement.contentDocument;
  176. } catch (error) {
  177. // ignored
  178. }
  179. if (frameDoc) {
  180. try {
  181. const frameWindow = frameElement.contentWindow;
  182. frameWindow.stop();
  183. processFrames(frameDoc, frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  184. framesData.push(getFrameData(frameDoc, frameWindow, windowId, options));
  185. } catch (error) {
  186. framesData.push({ windowId, processed: true });
  187. }
  188. }
  189. });
  190. sendInitResponse({ framesData, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  191. delete doc.documentElement.dataset.requestedFrameId;
  192. }
  193. function cleanupFrames(frameElements, parentWindowId, sessionId) {
  194. frameElements.forEach((frameElement, frameIndex) => {
  195. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  196. frameElement.removeAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME);
  197. try {
  198. sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId });
  199. } catch (error) {
  200. /* ignored */
  201. }
  202. });
  203. frameElements.forEach((frameElement, frameIndex) => {
  204. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  205. let frameDoc;
  206. try {
  207. frameDoc = frameElement.contentDocument;
  208. } catch (error) {
  209. // ignored
  210. }
  211. if (frameDoc) {
  212. try {
  213. cleanupFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), windowId, sessionId);
  214. } catch (error) {
  215. // ignored
  216. }
  217. }
  218. });
  219. }
  220. function sendInitResponse(message) {
  221. message.method = INIT_RESPONSE_MESSAGE;
  222. try {
  223. top.frameTree.initResponse(message);
  224. } catch (error) {
  225. sendMessage(top, message, true);
  226. }
  227. }
  228. function sendMessage(targetWindow, message, useChannel) {
  229. if (targetWindow == top && this.browser && browser.runtime && browser.runtime.sendMessage) {
  230. browser.runtime.sendMessage(message);
  231. } else {
  232. if (useChannel) {
  233. const channel = new MessageChannel();
  234. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  235. channel.port1.postMessage(message);
  236. } else {
  237. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  238. }
  239. }
  240. }
  241. function getFrameData(document, window, windowId, options) {
  242. const docData = docHelper.preProcessDoc(document, window, options);
  243. const content = docHelper.serialize(document);
  244. docHelper.postProcessDoc(document, options);
  245. const baseURI = document.baseURI.split("#")[0];
  246. return {
  247. windowId,
  248. content,
  249. baseURI,
  250. title: document.title,
  251. stylesheetsData: docData.stylesheetsData,
  252. imageData: docData.imageData,
  253. postersData: docData.postersData,
  254. canvasData: docData.canvasData,
  255. fontsData: docData.fontsData,
  256. usedFonts: docData.usedFonts,
  257. shadowRootsData: docData.shadowRootsData,
  258. processed: true
  259. };
  260. }
  261. })();