content-frame-tree.js 14 KB

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