content-frame-tree.js 12 KB

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