content-frame-tree.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global window, top, document, addEventListener, docHelper, MessageChannel, lazyLoader, browser, setTimeout */
  21. this.frameTree = this.frameTree || (() => {
  22. const MESSAGE_PREFIX = "__frameTree__::";
  23. const FRAMES_CSS_SELECTOR = "iframe, frame, object[type=\"text/html\"][data]";
  24. const INIT_REQUEST_MESSAGE = "initRequest";
  25. const CLEANUP_REQUEST_MESSAGE = "cleanupRequest";
  26. const INIT_RESPONSE_MESSAGE = "initResponse";
  27. const TARGET_ORIGIN = "*";
  28. const TIMEOUT_INIT_REQUEST_MESSAGE = 750;
  29. const TOP_WINDOW_ID = "0";
  30. const WINDOW_ID_SEPARATOR = ".";
  31. const TOP_WINDOW = window == top;
  32. const sessions = new Map();
  33. let windowId;
  34. if (TOP_WINDOW) {
  35. windowId = TOP_WINDOW_ID;
  36. if (this.browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
  37. browser.runtime.onMessage.addListener(message => {
  38. if (message.method == INIT_RESPONSE_MESSAGE) {
  39. initResponse(message);
  40. }
  41. });
  42. }
  43. }
  44. addEventListener("message", event => {
  45. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  46. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  47. if (!TOP_WINDOW && message.method == INIT_REQUEST_MESSAGE) {
  48. window.stop();
  49. initRequest(message);
  50. if (message.options.loadDeferredImages && window.lazyLoader) {
  51. lazyLoader.process(message.options);
  52. }
  53. } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
  54. cleanupRequest(message);
  55. } else if (message.method == INIT_RESPONSE_MESSAGE) {
  56. const port = event.ports[0];
  57. port.onmessage = event => initResponse(event.data);
  58. }
  59. event.preventDefault();
  60. event.stopPropagation();
  61. }
  62. }, true);
  63. return {
  64. getAsync: async options => {
  65. const sessionId = options.sessionId || 0;
  66. options = JSON.parse(JSON.stringify(options));
  67. return new Promise(resolve => {
  68. sessions.set(sessionId, { frames: [], resolve });
  69. initRequest({ windowId, sessionId, options });
  70. });
  71. },
  72. getSync: options => {
  73. const sessionId = options.sessionId || 0;
  74. options = JSON.parse(JSON.stringify(options));
  75. sessions.set(sessionId, { frames: [] });
  76. initRequest({ windowId, sessionId, options });
  77. return sessions.get(sessionId).frames;
  78. },
  79. cleanup: options => {
  80. const sessionId = options.sessionId || 0;
  81. options = JSON.parse(JSON.stringify(options));
  82. cleanupRequest({ windowId, sessionId, options });
  83. },
  84. initResponse,
  85. TIMEOUT_INIT_REQUEST_MESSAGE
  86. };
  87. function initRequest(message) {
  88. const sessionId = message.sessionId;
  89. if (!TOP_WINDOW) {
  90. windowId = message.windowId;
  91. }
  92. processFrames(document.querySelectorAll(FRAMES_CSS_SELECTOR), message.options, windowId, sessionId);
  93. if (!TOP_WINDOW) {
  94. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId });
  95. }
  96. }
  97. function cleanupRequest(message) {
  98. const sessionId = message.sessionId;
  99. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  100. if (!TOP_WINDOW) {
  101. windowId = message.windowId;
  102. }
  103. cleanupFrames(frameElements, message.options, windowId, sessionId);
  104. }
  105. function initResponse(message) {
  106. const windowData = sessions.get(message.sessionId);
  107. if (windowData) {
  108. if (message.requestedFrameId) {
  109. windowData.requestedFrameId = message.requestedFrameId;
  110. }
  111. message.framesData.forEach(messageFrameData => {
  112. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  113. if (!frameData) {
  114. frameData = { windowId: messageFrameData.windowId };
  115. windowData.frames.push(frameData);
  116. }
  117. if (!frameData.processed) {
  118. frameData.content = messageFrameData.content;
  119. frameData.baseURI = messageFrameData.baseURI;
  120. frameData.title = messageFrameData.title;
  121. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  122. frameData.imageData = messageFrameData.imageData;
  123. frameData.postersData = messageFrameData.postersData;
  124. frameData.canvasData = messageFrameData.canvasData;
  125. frameData.fontsData = messageFrameData.fontsData;
  126. frameData.usedFonts = messageFrameData.usedFonts;
  127. frameData.shadowRootContents = messageFrameData.shadowRootContents;
  128. frameData.processed = messageFrameData.processed;
  129. }
  130. });
  131. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  132. if (!remainingFrames) {
  133. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  134. if (windowData.resolve) {
  135. if (windowData.requestedFrameId) {
  136. windowData.frames.forEach(frameData => {
  137. if (frameData.windowId == windowData.requestedFrameId) {
  138. frameData.requestedFrame = true;
  139. }
  140. });
  141. }
  142. windowData.resolve(windowData.frames);
  143. }
  144. sessions.delete(message.sessionId);
  145. }
  146. }
  147. }
  148. function processFrames(frameElements, options, parentWindowId, sessionId) {
  149. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  150. if (frameElements.length) {
  151. processFramesSync(frameElements, options, parentWindowId, sessionId);
  152. }
  153. }
  154. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  155. const framesData = [];
  156. frameElements.forEach((frameElement, frameIndex) => {
  157. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  158. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, windowId);
  159. framesData.push({ windowId });
  160. try {
  161. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  162. } catch (error) {
  163. /* ignored */
  164. }
  165. setTimeout(() => sendInitResponse({ framesData: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
  166. });
  167. sendInitResponse({ framesData, sessionId });
  168. }
  169. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  170. const framesData = [];
  171. frameElements.forEach((frameElement, frameIndex) => {
  172. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  173. let frameDoc;
  174. try {
  175. frameDoc = frameElement.contentDocument;
  176. } catch (error) {
  177. // ignored
  178. }
  179. if (frameDoc) {
  180. try {
  181. frameElement.contentWindow.stop();
  182. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  183. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  184. } catch (error) {
  185. framesData.push({ windowId, processed: true });
  186. }
  187. }
  188. });
  189. sendInitResponse({ framesData, sessionId, requestedFrameId: this.frameTree.requestedFrameId && parentWindowId });
  190. }
  191. function cleanupFrames(frameElements, options, parentWindowId, sessionId) {
  192. frameElements.forEach((frameElement, frameIndex) => {
  193. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  194. frameElement.removeAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME);
  195. try {
  196. sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId, options });
  197. } catch (error) {
  198. /* ignored */
  199. }
  200. });
  201. frameElements.forEach((frameElement, frameIndex) => {
  202. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  203. let frameDoc;
  204. try {
  205. frameDoc = frameElement.contentDocument;
  206. } catch (error) {
  207. // ignored
  208. }
  209. if (frameDoc) {
  210. try {
  211. cleanupFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  212. } catch (error) {
  213. // ignored
  214. }
  215. }
  216. });
  217. }
  218. function sendInitResponse(message) {
  219. message.method = INIT_RESPONSE_MESSAGE;
  220. try {
  221. top.frameTree.initResponse(message);
  222. } catch (error) {
  223. sendMessage(top, message, true);
  224. }
  225. }
  226. function sendMessage(targetWindow, message, useChannel) {
  227. if (targetWindow == top && this.browser && browser.runtime && browser.runtime.sendMessage) {
  228. browser.runtime.sendMessage(message);
  229. } else {
  230. if (useChannel) {
  231. const channel = new MessageChannel();
  232. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  233. channel.port1.postMessage(message);
  234. } else {
  235. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  236. }
  237. }
  238. }
  239. function getFrameData(document, window, windowId, options) {
  240. const docData = docHelper.preProcessDoc(document, window, options);
  241. const content = docHelper.serialize(document);
  242. docHelper.postProcessDoc(document, options);
  243. const baseURI = document.baseURI.split("#")[0];
  244. return {
  245. windowId,
  246. content,
  247. baseURI,
  248. title: document.title,
  249. stylesheetContents: docData.stylesheetContents,
  250. imageData: docData.imageData,
  251. postersData: docData.postersData,
  252. canvasData: docData.canvasData,
  253. fontsData: docData.fontsData,
  254. usedFonts: docData.usedFonts,
  255. shadowRootContents: docData.shadowRootContents,
  256. processed: true
  257. };
  258. }
  259. })();