content-frame-tree.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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, timeout, MessageChannel, superFetch, fetch, TextDecoder, DOMParser, lazyLoader, setTimeout, browser */
  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 PREFIX_VALID_FRAME_URL = /^https?:\/\//;
  30. const TOP_WINDOW_ID = "0";
  31. const WINDOW_ID_SEPARATOR = ".";
  32. const TOP_WINDOW = window == top;
  33. const sessions = new Map();
  34. let windowId;
  35. if (TOP_WINDOW) {
  36. windowId = TOP_WINDOW_ID;
  37. if (this.browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
  38. browser.runtime.onMessage.addListener(message => {
  39. if (message.method == INIT_RESPONSE_MESSAGE) {
  40. initResponse(message);
  41. }
  42. });
  43. }
  44. }
  45. addEventListener("message", event => {
  46. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
  47. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
  48. if (!TOP_WINDOW && message.method == INIT_REQUEST_MESSAGE) {
  49. window.stop();
  50. initRequest(message);
  51. if (message.options.loadDeferredImages && window.lazyLoader) {
  52. lazyLoader.process(message.options);
  53. }
  54. } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
  55. cleanupRequest(message);
  56. } else if (message.method == INIT_RESPONSE_MESSAGE) {
  57. const port = event.ports[0];
  58. port.onmessage = event => initResponse(event.data);
  59. }
  60. event.preventDefault();
  61. event.stopPropagation();
  62. }
  63. }, true);
  64. return {
  65. getAsync: async options => {
  66. const sessionId = options.sessionId || 0;
  67. options = JSON.parse(JSON.stringify(options));
  68. return new Promise(resolve => {
  69. sessions.set(sessionId, { frames: [], resolve });
  70. initRequest({ windowId, sessionId, options });
  71. });
  72. },
  73. getSync: options => {
  74. const sessionId = options.sessionId || 0;
  75. options = JSON.parse(JSON.stringify(options));
  76. sessions.set(sessionId, { frames: [] });
  77. initRequest({ windowId, sessionId, options });
  78. return sessions.get(sessionId).frames;
  79. },
  80. cleanup: options => {
  81. const sessionId = options.sessionId || 0;
  82. options = JSON.parse(JSON.stringify(options));
  83. cleanupRequest({ windowId, sessionId, options });
  84. },
  85. initResponse,
  86. TIMEOUT_INIT_REQUEST_MESSAGE
  87. };
  88. function initRequest(message) {
  89. const sessionId = message.sessionId;
  90. const frameElements = document.querySelectorAll(FRAMES_CSS_SELECTOR);
  91. if (!TOP_WINDOW) {
  92. windowId = message.windowId;
  93. sendInitResponse({ framesData: [getFrameData(document, window, windowId, message.options)], sessionId });
  94. }
  95. processFrames(frameElements, message.options, windowId, sessionId);
  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. message.framesData.forEach(messageFrameData => {
  109. let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
  110. if (!frameData) {
  111. frameData = { windowId: messageFrameData.windowId };
  112. windowData.frames.push(frameData);
  113. }
  114. if (!frameData.processed) {
  115. frameData.content = messageFrameData.content;
  116. frameData.baseURI = messageFrameData.baseURI;
  117. frameData.title = messageFrameData.title;
  118. frameData.stylesheetContents = messageFrameData.stylesheetContents;
  119. frameData.imageData = messageFrameData.imageData;
  120. frameData.postersData = messageFrameData.postersData;
  121. frameData.canvasData = messageFrameData.canvasData;
  122. frameData.fontsData = messageFrameData.fontsData;
  123. frameData.usedFonts = messageFrameData.usedFonts;
  124. frameData.shadowRootContents = messageFrameData.shadowRootContents;
  125. frameData.processed = messageFrameData.processed;
  126. }
  127. });
  128. const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
  129. if (!remainingFrames) {
  130. windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
  131. if (windowData.resolve) {
  132. windowData.resolve(windowData.frames);
  133. sessions.delete(message.sessionId);
  134. }
  135. }
  136. }
  137. }
  138. function processFrames(frameElements, options, parentWindowId, sessionId) {
  139. processFramesAsync(frameElements, options, parentWindowId, sessionId);
  140. if (frameElements.length) {
  141. processFramesSync(frameElements, options, parentWindowId, sessionId);
  142. }
  143. }
  144. function processFramesAsync(frameElements, options, parentWindowId, sessionId) {
  145. const framesData = [];
  146. frameElements.forEach((frameElement, frameIndex) => {
  147. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  148. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, windowId);
  149. framesData.push({ windowId });
  150. try {
  151. sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
  152. } catch (error) {
  153. /* ignored */
  154. }
  155. setTimeout(async () => {
  156. let frameDoc;
  157. if (frameElement.src && frameElement.src.match(PREFIX_VALID_FRAME_URL)) {
  158. frameDoc = await getFrameDoc(frameElement.src, parentWindowId);
  159. }
  160. if (frameDoc) {
  161. sendInitResponse({ framesData: [getFrameData(frameDoc, null, windowId, options)] });
  162. timeout.set(() => sendInitResponse({ framesData: [{ windowId, processed: true }], sessionId }));
  163. } else {
  164. sendInitResponse({ framesData: [{ windowId, processed: true }], sessionId });
  165. }
  166. }, TIMEOUT_INIT_REQUEST_MESSAGE);
  167. });
  168. sendInitResponse({ framesData, sessionId });
  169. }
  170. function processFramesSync(frameElements, options, parentWindowId, sessionId) {
  171. const framesData = [];
  172. frameElements.forEach((frameElement, frameIndex) => {
  173. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  174. let frameDoc;
  175. try {
  176. frameDoc = frameElement.contentDocument;
  177. } catch (error) {
  178. // ignored
  179. }
  180. if (frameDoc) {
  181. try {
  182. frameElement.contentWindow.stop();
  183. processFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  184. framesData.push(getFrameData(frameDoc, frameElement.contentWindow, windowId, options));
  185. } catch (error) {
  186. framesData.push({ windowId, processed: true });
  187. }
  188. }
  189. });
  190. sendInitResponse({ framesData, sessionId });
  191. }
  192. function cleanupFrames(frameElements, options, parentWindowId, sessionId) {
  193. frameElements.forEach((frameElement, frameIndex) => {
  194. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  195. frameElement.removeAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME);
  196. try {
  197. sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId, options });
  198. } catch (error) {
  199. /* ignored */
  200. }
  201. });
  202. frameElements.forEach((frameElement, frameIndex) => {
  203. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  204. let frameDoc;
  205. try {
  206. frameDoc = frameElement.contentDocument;
  207. } catch (error) {
  208. // ignored
  209. }
  210. if (frameDoc) {
  211. try {
  212. cleanupFrames(frameDoc.querySelectorAll(FRAMES_CSS_SELECTOR), options, windowId, sessionId);
  213. } catch (error) {
  214. // ignored
  215. }
  216. }
  217. });
  218. }
  219. function sendInitResponse(message) {
  220. message.method = INIT_RESPONSE_MESSAGE;
  221. try {
  222. top.frameTree.initResponse(message);
  223. } catch (error) {
  224. sendMessage(top, message, true);
  225. }
  226. }
  227. function sendMessage(targetWindow, message, useChannel) {
  228. if (targetWindow == top && this.browser && browser.runtime && browser.runtime.sendMessage) {
  229. browser.runtime.sendMessage(message);
  230. } else {
  231. if (useChannel) {
  232. const channel = new MessageChannel();
  233. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method }), TARGET_ORIGIN, [channel.port2]);
  234. channel.port1.postMessage(message);
  235. } else {
  236. targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
  237. }
  238. }
  239. }
  240. async function getFrameDoc(frameUrl, parentWindowId) {
  241. let frameContent;
  242. try {
  243. frameContent = await ((typeof superFetch !== "undefined" && superFetch.fetch) || fetch)(frameUrl);
  244. } catch (error) {
  245. /* ignored */
  246. }
  247. if (frameContent && frameContent.status >= 400 && superFetch.hostFetch) {
  248. try {
  249. frameContent = await superFetch.hostFetch(frameUrl);
  250. } catch (error) {
  251. /* ignored */
  252. }
  253. }
  254. if (frameContent) {
  255. const contentType = frameContent.headers && frameContent.headers.get("content-type");
  256. let charset, mimeType;
  257. if (contentType) {
  258. const matchContentType = contentType.toLowerCase().split(";");
  259. mimeType = matchContentType[0].trim();
  260. if (!mimeType.includes("/")) {
  261. mimeType = "text/html";
  262. }
  263. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  264. if (charsetValue) {
  265. const matchCharset = charsetValue.match(/^charset=(.*)/);
  266. if (matchCharset) {
  267. charset = docHelper.removeQuotes(matchCharset[1]);
  268. }
  269. }
  270. }
  271. let doc;
  272. try {
  273. const buffer = await frameContent.arrayBuffer();
  274. const content = (new TextDecoder(charset)).decode(buffer);
  275. const domParser = new DOMParser();
  276. doc = domParser.parseFromString(content, mimeType);
  277. } catch (error) {
  278. /* ignored */
  279. }
  280. if (doc) {
  281. const frameElements = doc.documentElement.querySelectorAll(FRAMES_CSS_SELECTOR);
  282. frameElements.forEach((frameElement, frameIndex) => {
  283. const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
  284. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, windowId);
  285. });
  286. return doc;
  287. }
  288. }
  289. }
  290. function getFrameData(document, window, windowId, options) {
  291. const docData = docHelper.preProcessDoc(document, window, options);
  292. const content = docHelper.serialize(document);
  293. docHelper.postProcessDoc(document, options);
  294. const baseURI = document.baseURI.split("#")[0];
  295. return {
  296. windowId,
  297. content,
  298. baseURI,
  299. title: document.title,
  300. stylesheetContents: docData.stylesheetContents,
  301. imageData: docData.imageData,
  302. postersData: docData.postersData,
  303. canvasData: docData.canvasData,
  304. fontsData: docData.fontsData,
  305. usedFonts: docData.usedFonts,
  306. shadowRootContents: docData.shadowRootContents,
  307. processed: true
  308. };
  309. }
  310. })();