hooks-frame.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 browser, window, addEventListener, dispatchEvent, CustomEvent, document, HTMLDocument, FileReader, Blob, screen, Element, UIEvent */
  24. this.hooksFrame = this.hooksFrame || (() => {
  25. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  26. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  27. const LOAD_IMAGE_EVENT = "single-file-load-image";
  28. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  29. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  30. const fontFaces = [];
  31. if (document instanceof HTMLDocument) {
  32. let scriptElement = document.createElement("script");
  33. scriptElement.src = browser.runtime.getURL("/lib/hooks/hooks-web.js");
  34. (document.documentElement || document).appendChild(scriptElement);
  35. scriptElement.remove();
  36. scriptElement = document.createElement("script");
  37. scriptElement.textContent = `(${hook.toString()})(${JSON.stringify({ LOAD_DEFERRED_IMAGES_START_EVENT, LOAD_DEFERRED_IMAGES_END_EVENT, NEW_FONT_FACE_EVENT })})`;
  38. (document.documentElement || document).appendChild(scriptElement);
  39. scriptElement.remove();
  40. addEventListener(NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  41. }
  42. return {
  43. getFontsData: () => fontFaces,
  44. loadDeferredImagesStart: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_START_EVENT)),
  45. loadDeferredImagesEnd: () => dispatchEvent(new CustomEvent(LOAD_DEFERRED_IMAGES_END_EVENT)),
  46. LOAD_IMAGE_EVENT,
  47. IMAGE_LOADED_EVENT
  48. };
  49. function hook(constants) {
  50. const {
  51. LOAD_DEFERRED_IMAGES_START_EVENT,
  52. LOAD_DEFERRED_IMAGES_END_EVENT,
  53. NEW_FONT_FACE_EVENT
  54. } = constants;
  55. const FONT_STYLE_PROPERTIES = {
  56. family: "font-family",
  57. style: "font-style",
  58. weight: "font-weight",
  59. stretch: "font-stretch",
  60. unicodeRange: "unicode-range",
  61. variant: "font-variant",
  62. featureSettings: "font-feature-settings"
  63. };
  64. const requestAnimationFrame = window.requestAnimationFrame;
  65. const cancelAnimationFrame = window.cancelAnimationFrame;
  66. const observers = new Map();
  67. const observedElements = new Map();
  68. let loadDeferredImages;
  69. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  70. loadDeferredImages = true;
  71. const docBoundingRect = document.documentElement.getBoundingClientRect();
  72. Array.from(observers).forEach(([intersectionObserver, observer]) => {
  73. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  74. observer.callback(observedElements.get(intersectionObserver).map(target => {
  75. const boundingClientRect = target.getBoundingClientRect();
  76. const isIntersecting = true;
  77. const intersectionRatio = 1;
  78. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  79. const time = 0;
  80. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  81. }), intersectionObserver);
  82. });
  83. if (pendingRequestAnimationFrameCalls.size) {
  84. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  85. cancelAnimationFrame(id);
  86. callback();
  87. });
  88. }
  89. });
  90. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  91. loadDeferredImages = false;
  92. });
  93. let warningRequestAnimationFrameDisplayed;
  94. const pendingRequestAnimationFrameCalls = new Map();
  95. let lastTimestamp = 0;
  96. let errorDetected;
  97. window.requestAnimationFrame = function (callback) {
  98. if (!warningRequestAnimationFrameDisplayed) {
  99. console.warn("SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images."); // eslint-disable-line no-console
  100. warningRequestAnimationFrameDisplayed = true;
  101. }
  102. let requestId;
  103. if (loadDeferredImages && !errorDetected) {
  104. try {
  105. requestId = 0;
  106. callback(lastTimestamp);
  107. } catch (error) {
  108. errorDetected = true;
  109. requestId = requestAnimationFrame(timestamp => {
  110. lastTimestamp = timestamp;
  111. callback(timestamp);
  112. });
  113. }
  114. } else {
  115. if (!loadDeferredImages) {
  116. errorDetected = false;
  117. }
  118. requestId = requestAnimationFrame(timestamp => {
  119. pendingRequestAnimationFrameCalls.delete(requestId);
  120. lastTimestamp = timestamp;
  121. callback(timestamp);
  122. });
  123. pendingRequestAnimationFrameCalls.set(requestId, callback);
  124. }
  125. return requestId;
  126. };
  127. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  128. window.cancelAnimationFrame = function (requestId) {
  129. pendingRequestAnimationFrameCalls.delete(requestId);
  130. return cancelAnimationFrame(requestId);
  131. };
  132. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  133. if (window.FontFace) {
  134. const FontFace = window.FontFace;
  135. let warningFontFaceDisplayed;
  136. window.FontFace = function () {
  137. if (!warningFontFaceDisplayed) {
  138. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  139. warningFontFaceDisplayed = true;
  140. }
  141. const detail = {};
  142. detail["font-family"] = arguments[0];
  143. detail.src = arguments[1];
  144. const descriptors = arguments[2];
  145. if (descriptors) {
  146. Object.keys(descriptors).forEach(descriptor => {
  147. if (FONT_STYLE_PROPERTIES[descriptor]) {
  148. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  149. }
  150. });
  151. }
  152. if (detail.src instanceof ArrayBuffer) {
  153. const reader = new FileReader();
  154. reader.readAsDataURL(new Blob([detail.src]));
  155. reader.addEventListener("load", () => {
  156. detail.src = "url(" + reader.result + ")";
  157. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  158. });
  159. } else {
  160. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  161. }
  162. return new FontFace(...arguments);
  163. };
  164. window.FontFace.toString = function () { return "function FontFace() { [native code]"; };
  165. }
  166. if (window.IntersectionObserver) {
  167. const IntersectionObserver = window.IntersectionObserver;
  168. const observeIntersection = IntersectionObserver.prototype.observe;
  169. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  170. let warningIntersectionObserverDisplayed;
  171. window.IntersectionObserver = function () {
  172. if (!warningIntersectionObserverDisplayed) {
  173. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  174. warningIntersectionObserverDisplayed = true;
  175. }
  176. const intersectionObserver = new IntersectionObserver(...arguments);
  177. const callback = arguments[0];
  178. const options = arguments[1];
  179. intersectionObserver.observe = function (targetElement) {
  180. let targetElements = observedElements.get(intersectionObserver);
  181. if (!targetElements) {
  182. targetElements = [];
  183. observedElements.set(intersectionObserver, targetElements);
  184. }
  185. targetElements.push(targetElement);
  186. return observeIntersection.call(intersectionObserver, targetElement);
  187. };
  188. intersectionObserver.unobserve = function (targetElement) {
  189. let targetElements = observedElements.get(intersectionObserver);
  190. if (targetElements) {
  191. targetElements = targetElements.filter(element => element <= targetElement);
  192. if (targetElements.length) {
  193. observedElements.set(intersectionObserver, targetElements);
  194. } else {
  195. observedElements.delete(intersectionObserver);
  196. }
  197. }
  198. return unobserveIntersection.call(intersectionObserver, targetElement);
  199. };
  200. observers.set(intersectionObserver, { callback, options });
  201. return intersectionObserver;
  202. };
  203. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code]"; };
  204. }
  205. }
  206. })();