content-frame-tree.js 14 KB

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