content-frame-tree.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 = "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 == 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", 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. initRequest(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(resolve => {
  80. sessions.set(sessionId, { frames: [], resolve });
  81. initRequest({ 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. initRequest({ 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 initRequest(message) {
  99. const sessionId = message.sessionId;
  100. if (!TOP_WINDOW) {
  101. windowId = window.frameId = message.windowId;
  102. }
  103. processFrames(document, message.options, windowId, sessionId);
  104. if (!TOP_WINDOW) {
  105. sendInitResponse({ frames: [getFrameData(document, window, windowId, message.options)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
  106. delete document.documentElement.dataset.requestedFrameId;
  107. }
  108. }
  109. function cleanupRequest(message) {
  110. const sessionId = message.sessionId;
  111. cleanupFrames(getFrames(document), message.windowId, sessionId);
  112. }
  113. function initResponse(message) {
  114. const windowData = sessions.get(message.sessionId);
  115. if (windowData) {
  116. if (message.requestedFrameId) {
  117. windowData.requestedFrameId = message.requestedFrameId;
  118. }
  119. message.frames.forEach(messageFrameData => {
  120. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  121. if (!frameData) {
  122. frameData = { windowId: messageFrameData.windowId };
  123. windowData.frames.push(frameData);
  124. }
  125. if (!frameData.processed) {
  126. frameData.content = messageFrameData.content;
  127. frameData.baseURI = messageFrameData.baseURI;
  128. frameData.title = messageFrameData.title;
  129. frameData.canvases = messageFrameData.canvases;
  130. frameData.fonts = messageFrameData.fonts;
  131. frameData.stylesheets = messageFrameData.stylesheets;
  132. frameData.images = messageFrameData.images;
  133. frameData.posters = messageFrameData.posters;
  134. frameData.usedFonts = messageFrameData.usedFonts;
  135. frameData.shadowRoots = messageFrameData.shadowRoots;
  136. frameData.imports = messageFrameData.imports;
  137. frameData.processed = messageFrameData.processed;
  138. }
  139. });
  140. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  141. if (!remainingFrames) {
  142. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  143. if (windowData.resolve) {
  144. if (windowData.requestedFrameId) {
  145. windowData.frames.forEach(frameData => {
  146. if (frameData.windowId == windowData.requestedFrameId) {
  147. frameData.requestedFrame = true;
  148. }
  149. });
  150. }
  151. windowData.resolve(windowData.frames);
  152. }
  153. }
  154. }
  155. }
  156. function processFrames(doc, options, parentWindowId, sessionId) {
  157. const frameElements = getFrames(doc);
  158. processFramesAsync(doc, frameElements, options, parentWindowId, sessionId);
  159. if (frameElements.length) {
  160. processFramesSync(doc, frameElements, options, parentWindowId, sessionId);
  161. }
  162. }
  163. function processFramesAsync(doc, frameElements, options, parentWindowId, sessionId) {
  164. const frames = [];
  165. frameElements.forEach((frameElement, frameIndex) => {
  166. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  167. frameElement.setAttribute(singlefile.lib.helper.WIN_ID_ATTRIBUTE_NAME, windowId);
  168. frames.push({ windowId });
  169. try {
  170. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  171. } catch (error) {
  172. // ignored
  173. }
  174. setTimeout.call(window, () => sendInitResponse({ frames: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  175. });
  176. sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  177. delete doc.documentElement.dataset.requestedFrameId;
  178. }
  179. function processFramesSync(doc, frameElements, options, parentWindowId, sessionId) {
  180. const frames = [];
  181. frameElements.forEach((frameElement, frameIndex) => {
  182. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  183. let frameDoc;
  184. try {
  185. frameDoc = frameElement.contentDocument;
  186. } catch (error) {
  187. // ignored
  188. }
  189. if (frameDoc) {
  190. try {
  191. const frameWindow = frameElement.contentWindow;
  192. frameWindow.stop();
  193. processFrames(frameDoc, options, windowId, sessionId);
  194. frames.push(getFrameData(frameDoc, frameWindow, windowId, options));
  195. } catch (error) {
  196. frames.push({ windowId, processed: true });
  197. }
  198. }
  199. });
  200. sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
  201. delete doc.documentElement.dataset.requestedFrameId;
  202. }
  203. function cleanupFrames(frameElements, parentWindowId, sessionId) {
  204. frameElements.forEach((frameElement, frameIndex) => {
  205. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  206. frameElement.removeAttribute(singlefile.lib.helper.WIN_ID_ATTRIBUTE_NAME);
  207. try {
  208. sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId });
  209. } catch (error) {
  210. // ignored
  211. }
  212. });
  213. frameElements.forEach((frameElement, frameIndex) => {
  214. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  215. let frameDoc;
  216. try {
  217. frameDoc = frameElement.contentDocument;
  218. } catch (error) {
  219. // ignored
  220. }
  221. if (frameDoc) {
  222. try {
  223. cleanupFrames(getFrames(frameDoc), windowId, sessionId);
  224. } catch (error) {
  225. // ignored
  226. }
  227. }
  228. });
  229. }
  230. function sendInitResponse(message) {
  231. message.method = INIT_RESPONSE_MESSAGE;
  232. try {
  233. top.singlefile.lib.frameTree.content.frames.initResponse(message);
  234. } catch (error) {
  235. sendMessage(top, message, true);
  236. }
  237. }
  238. function sendMessage(targetWindow, message, useChannel) {
  239. if (targetWindow == top && browser && browser.runtime && browser.runtime.sendMessage) {
  240. browser.runtime.sendMessage(message);
  241. } else {
  242. if (useChannel) {
  243. const channel = new MessageChannel();
  244. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  245. channel.port1.postMessage(message);
  246. } else {
  247. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  248. }
  249. }
  250. }
  251. function getFrameData(document, window, windowId, options) {
  252. const helper = singlefile.lib.helper;
  253. const docData = helper.preProcessDoc(document, window, options);
  254. const content = helper.serialize(document);
  255. helper.postProcessDoc(document, docData.markedElements);
  256. const baseURI = document.baseURI.split("#")[0];
  257. return {
  258. windowId,
  259. content,
  260. baseURI,
  261. title: document.title,
  262. canvases: docData.canvases,
  263. fonts: docData.fonts,
  264. stylesheets: docData.stylesheets,
  265. images: docData.images,
  266. posters: docData.posters,
  267. usedFonts: docData.usedFonts,
  268. shadowRoots: docData.shadowRoots,
  269. imports: docData.imports,
  270. processed: true
  271. };
  272. }
  273. function getFrames(document) {
  274. let frames = Array.from(document.querySelectorAll(FRAMES_CSS_SELECTOR));
  275. document.querySelectorAll(ALL_ELEMENTS_CSS_SELECTOR).forEach(element => {
  276. if (element.shadowRoot) {
  277. frames = frames.concat(...element.shadowRoot.querySelectorAll(FRAMES_CSS_SELECTOR));
  278. }
  279. });
  280. return frames;
  281. }
  282. })();