content-frame-tree.js 10 KB

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