frame-tree.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. * Copyright 2018 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 browser, window, top, document, HTMLHtmlElement, addEventListener, docHelper */
  21. this.FrameTree = this.FrameTree || (() => {
  22. const MESSAGE_PREFIX = "__FrameTree__";
  23. const TIMEOUT_INIT_REQUEST_MESSAGE = 500;
  24. const TIMEOUT_DATA_RESPONSE_MESSAGE = 500;
  25. const TIMEOUT_STEP = 100;
  26. const FrameTree = { getFramesData };
  27. const timeoutIds = [];
  28. const timeout = {
  29. set(fn, delay) {
  30. const id = timeoutIds.length;
  31. let elapsedTime = 0;
  32. timeoutIds[id] = setTimeout(step, 0);
  33. return id;
  34. function step() {
  35. if (elapsedTime < delay) {
  36. timeoutIds[id] = setTimeout(() => {
  37. elapsedTime += TIMEOUT_STEP;
  38. step();
  39. }, TIMEOUT_STEP);
  40. }
  41. else {
  42. fn();
  43. }
  44. }
  45. },
  46. clear(id) {
  47. if (timeoutIds[id]) {
  48. clearTimeout(timeoutIds[id]);
  49. timeoutIds[id] = null;
  50. }
  51. }
  52. };
  53. let framesData, dataRequestCallbacks, initResponseSent;
  54. if (window == top) {
  55. browser.runtime.onMessage.addListener(message => {
  56. if (message.method == "FrameTree.initRequest" && document.documentElement instanceof HTMLHtmlElement) {
  57. dataRequestCallbacks = new Map();
  58. framesData = [];
  59. initResponseSent = false;
  60. initRequest(message);
  61. }
  62. if (message.method == "FrameTree.getDataResponse") {
  63. getDataResponse(message);
  64. }
  65. });
  66. }
  67. browser.runtime.onMessage.addListener(message => {
  68. if (message.method == "FrameTree.getDataRequest" && FrameTree.windowId == message.windowId) {
  69. const docData = docHelper.preProcessDoc(document, window, message.options);
  70. browser.runtime.sendMessage({
  71. method: "FrameTree.getDataResponse",
  72. windowId: message.windowId,
  73. tabId: message.tabId,
  74. content: docHelper.serialize(document),
  75. emptyStyleRulesText: docData.emptyStyleRulesText,
  76. canvasData: docData.canvasData,
  77. baseURI: document.baseURI,
  78. title: document.title
  79. });
  80. docHelper.postProcessDoc(document, message.options);
  81. }
  82. });
  83. addEventListener("message", event => {
  84. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  85. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  86. if (message.method == "initRequest") {
  87. initRequest(message);
  88. } else if (message.method == "initResponse") {
  89. initResponse(message);
  90. } else if (message.method == "getDataResponse") {
  91. getDataResponse(message);
  92. }
  93. }
  94. }, false);
  95. return FrameTree;
  96. async function getFramesData(options) {
  97. await Promise.all(framesData.map(async frameData => {
  98. return new Promise(resolve => {
  99. dataRequestCallbacks.set(frameData.windowId, resolve);
  100. if (frameData.sameDomain) {
  101. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataRequest", windowId: frameData.windowId, options: { removeHiddenElements: options.removeHiddenElements, compressHTML: options.compressHTML } }), "*");
  102. } else {
  103. browser.runtime.sendMessage({
  104. method: "FrameTree.getDataRequest",
  105. windowId: frameData.windowId,
  106. options: { removeHiddenElements: options.removeHiddenElements, compressHTML: options.compressHTML }
  107. });
  108. }
  109. frameData.getDataResponseTimeout = timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: frameData.windowId }), "*"), TIMEOUT_DATA_RESPONSE_MESSAGE);
  110. });
  111. }));
  112. return framesData.sort((frame1, frame2) => frame2.windowId.split(".").length - frame1.windowId.split(".").length);
  113. }
  114. function initRequest(message) {
  115. FrameTree.windowId = message.windowId;
  116. FrameTree.index = message.index;
  117. const frameElements = document.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  118. if (frameElements.length) {
  119. setFramesWinId(MESSAGE_PREFIX, frameElements, message.options, FrameTree.index, FrameTree.windowId, window);
  120. } else {
  121. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: FrameTree.windowId, index: FrameTree.index }), "*");
  122. }
  123. }
  124. function initResponse(message) {
  125. if (window == top) {
  126. if (message.framesData) {
  127. message.framesData = message.framesData instanceof Array ? message.framesData : JSON.parse(message.framesData);
  128. framesData = framesData.concat(message.framesData);
  129. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  130. if (message.windowId != "0") {
  131. frameData.processed = true;
  132. }
  133. const pendingCount = framesData.filter(frameData => !frameData.processed).length;
  134. if (!pendingCount && !initResponseSent) {
  135. initResponseSent = true;
  136. browser.runtime.sendMessage({ method: "FrameTree.initResponse" });
  137. }
  138. }
  139. } else {
  140. FrameTree.windowId = message.windowId;
  141. FrameTree.index = message.index;
  142. }
  143. }
  144. function setFramesWinId(MESSAGE_PREFIX, frameElements, options, index, windowId, win) {
  145. const framesData = [];
  146. if (win != top) {
  147. win.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", windowId, index }), "*");
  148. }
  149. frameElements.forEach((frameElement, index) => {
  150. let src, sameDomain;
  151. try {
  152. sameDomain = Boolean(frameElement.contentDocument && frameElement.contentWindow && top.addEventListener && top);
  153. src = frameElement.src;
  154. } catch (error) {
  155. /* ignored */
  156. }
  157. framesData.push({ sameDomain, src, index, windowId: windowId + "." + index });
  158. });
  159. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData, windowId, index }), "*");
  160. frameElements.forEach((frameElement, index) => {
  161. const frameWinId = windowId + "." + index;
  162. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, frameWinId);
  163. let frameDoc, frameWindow, topWindow;
  164. let content, emptyStyleRulesText, canvasData;
  165. try {
  166. frameDoc = frameElement.contentDocument;
  167. frameWindow = frameElement.contentWindow;
  168. topWindow = top.addEventListener && top;
  169. } catch (error) {
  170. /* ignored */
  171. }
  172. if (frameWindow && frameDoc && topWindow) {
  173. setFramesWinId(MESSAGE_PREFIX, frameDoc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"), options, index, frameWinId, frameWindow);
  174. topWindow.addEventListener("message", onMessage, false);
  175. const docData = docHelper.preProcessDoc(frameDoc, frameWindow, options);
  176. content = docHelper.serialize(frameDoc);
  177. emptyStyleRulesText = docData.emptyStyleRulesText;
  178. canvasData = docData.canvasData;
  179. docHelper.postProcessDoc(frameDoc, options);
  180. } else if (frameWindow) {
  181. frameWindow.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initRequest", windowId: frameWinId, index, options }), "*");
  182. timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: frameWinId, index }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
  183. }
  184. function onMessage(event) {
  185. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  186. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  187. if (message.method == "getDataRequest" && message.windowId == frameWinId) {
  188. topWindow.removeEventListener("message", onMessage, false);
  189. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: message.windowId, content, baseURI: frameDoc.baseURI, title: document.title, emptyStyleRulesText, canvasData }), "*");
  190. }
  191. }
  192. }
  193. });
  194. }
  195. function getDataResponse(message) {
  196. delete message.tabId;
  197. delete message.method;
  198. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  199. timeout.clear(frameData.getDataResponseTimeout);
  200. frameData.content = message.content;
  201. frameData.baseURI = message.baseURI;
  202. frameData.title = message.title;
  203. frameData.emptyStyleRulesText = message.emptyStyleRulesText;
  204. frameData.canvasData = message.canvasData;
  205. dataRequestCallbacks.get(message.windowId)(message);
  206. }
  207. })();