content-frame-tree.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Copyright 2010-2019 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, MessageChannel, lazyLoader, browser, setTimeout */
  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 CLEANUP_REQUEST_MESSAGE = "cleanupRequest";
  26. const INIT_RESPONSE_MESSAGE = "frameTree.initResponse";
  27. const TARGET_ORIGIN = "*";
  28. const TIMEOUT_INIT_REQUEST_MESSAGE = 750;
  29. const TOP_WINDOW_ID = "0";
  30. const WINDOW_ID_SEPARATOR = ".";
  31. const TOP_WINDOW = window == top;
  32. const sessions = new Map();
  33. let windowId;
  34. if (TOP_WINDOW) {
  35. windowId = TOP_WINDOW_ID;
  36. if (this.browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
  37. browser.runtime.onMessage.addListener(message => {
  38. if (message.method == INIT_RESPONSE_MESSAGE) {
  39. initResponse(message);
  40. }
  41. });
  42. }
  43. }
  44. addEventListener("message", event => {
  45. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  46. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  47. if (!TOP_WINDOW && message.method == INIT_REQUEST_MESSAGE) {
  48. window.stop();
  49. initRequest(message);
  50. if (message.options.loadDeferredImages && window.lazyLoader) {
  51. lazyLoader.process(message.options);
  52. }
  53. } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
  54. cleanupRequest(message);
  55. } else if (!browser.runtime && message.method == INIT_RESPONSE_MESSAGE) {
  56. const port = event.ports[0];
  57. port.onmessage = event => initResponse(event.data);
  58. }
  59. event.preventDefault();
  60. event.stopPropagation();
  61. }
  62. }, true);
  63. return {
  64. getAsync: async options => {
  65. const sessionId = options.sessionId || 0;
  66. options = JSON.parse(JSON.stringify(options));
  67. return new Promise(resolve => {
  68. sessions.set(sessionId, { frames: [], resolve });
  69. initRequest({ windowId, sessionId, options });
  70. });
  71. },
  72. getSync: options => {
  73. const sessionId = options.sessionId || 0;
  74. options = JSON.parse(JSON.stringify(options));
  75. sessions.set(sessionId, { frames: [] });
  76. initRequest({ windowId, sessionId, options });
  77. return sessions.get(sessionId).frames;
  78. },
  79. cleanup: options => {
  80. const sessionId = options.sessionId || 0;
  81. cleanupRequest({ windowId, sessionId, options: { sessionId } });
  82. },
  83. initResponse,
  84. TIMEOUT_INIT_REQUEST_MESSAGE
  85. };
  86. function initRequest(message) {
  87. const sessionId = message.sessionId;
  88. if (!TOP_WINDOW) {
  89. windowId = message.windowId;
  90. }
  91. processFrames(document, document.querySelectorAll(FRAMES_CSS_SELECTOR), message.options, windowId, sessionId);
  92. if (!TOP_WINDOW) {
  93. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
  94. delete document.documentElement.dataset.requestedFrameId;
  95. }
  96. }
  97. function cleanupRequest(message) {
  98. const sessionId = message.sessionId;
  99. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  100. cleanupFrames(frameElements, message.windowId, sessionId);
  101. }
  102. function initResponse(message) {
  103. const windowData = sessions.get(message.sessionId);
  104. if (windowData) {
  105. if (message.requestedFrameId) {
  106. windowData.requestedFrameId = message.requestedFrameId;
  107. }
  108. message.framesData.forEach(messageFrameData => {
  109. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  110. if (!frameData) {
  111. frameData = { windowId: messageFrameData.windowId };
  112. windowData.frames.push(frameData);
  113. }
  114. if (!frameData.processed) {
  115. frameData.content = messageFrameData.content;
  116. frameData.baseURI = messageFrameData.baseURI;
  117. frameData.title = messageFrameData.title;
  118. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  119. frameData.imageData = messageFrameData.imageData;
  120. frameData.postersData = messageFrameData.postersData;
  121. frameData.canvasData = messageFrameData.canvasData;
  122. frameData.fontsData = messageFrameData.fontsData;
  123. frameData.usedFonts = messageFrameData.usedFonts;
  124. frameData.shadowRootContents = messageFrameData.shadowRootContents;
  125. frameData.processed = messageFrameData.processed;
  126. }
  127. });
  128. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  129. if (!remainingFrames) {
  130. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  131. if (windowData.resolve) {
  132. if (windowData.requestedFrameId) {
  133. windowData.frames.forEach(frameData => {
  134. if (frameData.windowId == windowData.requestedFrameId) {
  135. frameData.requestedFrame = true;
  136. }
  137. });
  138. }
  139. windowData.resolve(windowData.frames);
  140. }
  141. }
  142. }
  143. }
  144. function processFrames(doc, frameElements, options, parentWindowId, sessionId) {
  145. processFramesAsync(doc, frameElements, options, parentWindowId, sessionId);
  146. if (frameElements.length) {
  147. processFramesSync(doc, frameElements, options, parentWindowId, sessionId);
  148. }
  149. }
  150. function processFramesAsync(doc, frameElements, options, parentWindowId, sessionId) {
  151. const framesData = [];
  152. frameElements.forEach((frameElement, frameIndex) => {
  153. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  154. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, windowId);
  155. framesData.push({ windowId });
  156. try {
  157. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  158. } catch (error) {
  159. /* ignored */
  160. }
  161. setTimeout(() => sendInitResponse({ framesData: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  162. });
  163. sendInitResponse({ framesData, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  164. delete doc.documentElement.dataset.requestedFrameId;
  165. }
  166. function processFramesSync(doc, frameElements, options, parentWindowId, sessionId) {
  167. const framesData = [];
  168. frameElements.forEach((frameElement, frameIndex) => {
  169. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  170. let frameDoc;
  171. try {
  172. frameDoc = frameElement.contentDocument;
  173. } catch (error) {
  174. // ignored
  175. }
  176. if (frameDoc) {
  177. try {
  178. const frameWindow = frameElement.contentWindow;
  179. frameWindow.stop();
  180. processFrames(frameDoc, frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  181. framesData.push(getFrameData(frameDoc, frameWindow, windowId, options));
  182. } catch (error) {
  183. framesData.push({ windowId, processed: true });
  184. }
  185. }
  186. });
  187. sendInitResponse({ framesData, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  188. delete doc.documentElement.dataset.requestedFrameId;
  189. }
  190. function cleanupFrames(frameElements, parentWindowId, sessionId) {
  191. frameElements.forEach((frameElement, frameIndex) => {
  192. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  193. frameElement.removeAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME);
  194. try {
  195. sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId });
  196. } catch (error) {
  197. /* ignored */
  198. }
  199. });
  200. frameElements.forEach((frameElement, frameIndex) => {
  201. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  202. let frameDoc;
  203. try {
  204. frameDoc = frameElement.contentDocument;
  205. } catch (error) {
  206. // ignored
  207. }
  208. if (frameDoc) {
  209. try {
  210. cleanupFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), windowId, sessionId);
  211. } catch (error) {
  212. // ignored
  213. }
  214. }
  215. });
  216. }
  217. function sendInitResponse(message) {
  218. message.method = INIT_RESPONSE_MESSAGE;
  219. try {
  220. top.frameTree.initResponse(message);
  221. } catch (error) {
  222. sendMessage(top, message, true);
  223. }
  224. }
  225. function sendMessage(targetWindow, message, useChannel) {
  226. if (targetWindow == top && this.browser && browser.runtime && browser.runtime.sendMessage) {
  227. browser.runtime.sendMessage(message);
  228. } else {
  229. if (useChannel) {
  230. const channel = new MessageChannel();
  231. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  232. channel.port1.postMessage(message);
  233. } else {
  234. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  235. }
  236. }
  237. }
  238. function getFrameData(document, window, windowId, options) {
  239. const docData = docHelper.preProcessDoc(document, window, options);
  240. const content = docHelper.serialize(document);
  241. docHelper.postProcessDoc(document, options);
  242. const baseURI = document.baseURI.split("#")[0];
  243. return {
  244. windowId,
  245. content,
  246. baseURI,
  247. title: document.title,
  248. stylesheetContents: docData.stylesheetContents,
  249. imageData: docData.imageData,
  250. postersData: docData.postersData,
  251. canvasData: docData.canvasData,
  252. fontsData: docData.fontsData,
  253. usedFonts: docData.usedFonts,
  254. shadowRootContents: docData.shadowRootContents,
  255. processed: true
  256. };
  257. }
  258. })();