content-frame-tree.js 14 KB

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