content-hooks-frames-web.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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, addEventListener, dispatchEvent, CustomEvent, document, screen, Element, UIEvent, FileReader, Blob */
  24. (() => {
  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 BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
  28. const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
  29. const LOAD_IMAGE_EVENT = "single-file-load-image";
  30. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  31. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  32. const FONT_STYLE_PROPERTIES = {
  33. family: "font-family",
  34. style: "font-style",
  35. weight: "font-weight",
  36. stretch: "font-stretch",
  37. unicodeRange: "unicode-range",
  38. variant: "font-variant",
  39. featureSettings: "font-feature-settings"
  40. };
  41. const requestAnimationFrame = window.requestAnimationFrame;
  42. const cancelAnimationFrame = window.cancelAnimationFrame;
  43. const observers = new Map();
  44. const observedElements = new Map();
  45. let loadDeferredImages;
  46. addEventListener(LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  47. loadDeferredImages = true;
  48. const scrollingElement = document.scrollingElement || document.documentElement;
  49. const clientHeight = scrollingElement.clientHeight;
  50. const clientWidth = scrollingElement.clientWidth;
  51. const scrollHeight = Math.max(scrollingElement.scrollHeight - (clientHeight * .5), clientHeight);
  52. const scrollWidth = Math.max(scrollingElement.scrollWidth - (clientWidth * .5), clientWidth);
  53. scrollingElement.__defineGetter__("clientHeight", () => scrollHeight);
  54. scrollingElement.__defineGetter__("clientWidth", () => scrollWidth);
  55. screen.__defineGetter__("height", () => scrollHeight);
  56. screen.__defineGetter__("width", () => scrollWidth);
  57. if (!window._singleFile_getBoundingClientRect) {
  58. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  59. Element.prototype.getBoundingClientRect = function () {
  60. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  61. if (this == scrollingElement) {
  62. boundingRect.__defineGetter__("height", () => scrollHeight);
  63. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  64. boundingRect.__defineGetter__("width", () => scrollWidth);
  65. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  66. }
  67. return boundingRect;
  68. };
  69. window._singleFile_innerHeight = window.innerHeight;
  70. window._singleFile_innerWidth = window.innerWidth;
  71. window.__defineGetter__("innerHeight", () => scrollHeight);
  72. window.__defineGetter__("innerWidth", () => scrollWidth);
  73. }
  74. if (!window._singleFileImage) {
  75. const Image = window.Image;
  76. window._singleFileImage = window.Image;
  77. window.__defineGetter__("Image", function () {
  78. return function () {
  79. const image = new Image(...arguments);
  80. const result = new Image(...arguments);
  81. result.__defineSetter__("src", function (value) {
  82. image.src = value;
  83. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  84. });
  85. result.__defineGetter__("src", function () {
  86. return image.src;
  87. });
  88. result.__defineSetter__("srcset", function (value) {
  89. dispatchEvent(new CustomEvent(LOAD_IMAGE_EVENT));
  90. image.srcset = value;
  91. });
  92. result.__defineGetter__("srcset", function () {
  93. return image.srcset;
  94. });
  95. image.onload = image.onloadend = image.onerror = event => {
  96. dispatchEvent(new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  97. result.dispatchEvent(new UIEvent(event.type, event));
  98. };
  99. return result;
  100. };
  101. });
  102. }
  103. const zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  104. const zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  105. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  106. if (zoomFactor < 1) {
  107. const transform = document.documentElement.style.getPropertyValue("transform");
  108. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  109. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  110. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  111. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  112. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  113. dispatchEvent(new UIEvent("resize"));
  114. dispatchEvent(new UIEvent("scroll"));
  115. document.documentElement.style.setProperty("transform", transform, transformPriority);
  116. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  117. }
  118. dispatchEvent(new UIEvent("resize"));
  119. dispatchEvent(new UIEvent("scroll"));
  120. const docBoundingRect = scrollingElement.getBoundingClientRect();
  121. Array.from(observers, ([intersectionObserver, observer]) => {
  122. const rootBoundingRect = observer.options.root && observer.options.root.getBoundingClientRect();
  123. observer.callback(observedElements.get(intersectionObserver).map(target => {
  124. const boundingClientRect = target.getBoundingClientRect();
  125. const isIntersecting = true;
  126. const intersectionRatio = 1;
  127. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  128. const time = 0;
  129. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  130. }), intersectionObserver);
  131. });
  132. if (pendingRequestAnimationFrameCalls.size) {
  133. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  134. cancelAnimationFrame(id);
  135. callback();
  136. });
  137. }
  138. });
  139. addEventListener(LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  140. const scrollingElement = document.scrollingElement || document.documentElement;
  141. delete scrollingElement.clientHeight;
  142. delete scrollingElement.clientWidth;
  143. delete screen.height;
  144. delete screen.width;
  145. if (window._singleFile_getBoundingClientRect) {
  146. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  147. window.innerHeight = window._singleFile_innerHeight;
  148. window.innerWidth = window._singleFile_innerWidth;
  149. delete window._singleFile_getBoundingClientRect;
  150. delete window._singleFile_innerHeight;
  151. delete window._singleFile_innerWidth;
  152. }
  153. if (window._singleFileImage) {
  154. delete window.Image;
  155. window.Image = window._singleFileImage;
  156. delete window._singleFileImage;
  157. }
  158. loadDeferredImages = false;
  159. dispatchEvent(new UIEvent("resize"));
  160. dispatchEvent(new UIEvent("scroll"));
  161. });
  162. addEventListener(BLOCK_COOKIES_START_EVENT, () => {
  163. try {
  164. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  165. } catch (error) {
  166. // ignored
  167. }
  168. if (!window._singleFile_localStorage) {
  169. window._singleFile_localStorage = window.localStorage;
  170. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  171. }
  172. if (!window._singleFile_indexedDB) {
  173. window._singleFile_indexedDB = window.indexedDB;
  174. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  175. }
  176. });
  177. addEventListener(BLOCK_COOKIES_END_EVENT, () => {
  178. delete document.cookie;
  179. if (window._singleFile_localStorage) {
  180. delete window.localStorage;
  181. window.localStorage = window._singleFile_localStorage;
  182. delete window._singleFile_localStorage;
  183. }
  184. if (!window._singleFile_indexedDB) {
  185. delete window.indexedDB;
  186. window.indexedDB = window._singleFile_indexedDB;
  187. delete window._singleFile_indexedDB;
  188. }
  189. });
  190. let warningRequestAnimationFrameDisplayed;
  191. const pendingRequestAnimationFrameCalls = new Map();
  192. let lastTimestamp = 0;
  193. let errorDetected;
  194. window.requestAnimationFrame = function (callback) {
  195. if (!warningRequestAnimationFrameDisplayed) {
  196. console.warn("SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images in background tabs."); // eslint-disable-line no-console
  197. warningRequestAnimationFrameDisplayed = true;
  198. }
  199. let requestId;
  200. if (loadDeferredImages && !errorDetected) {
  201. try {
  202. requestId = 0;
  203. callback(lastTimestamp);
  204. } catch (error) {
  205. errorDetected = true;
  206. requestId = requestAnimationFrame(timestamp => {
  207. lastTimestamp = timestamp;
  208. callback(timestamp);
  209. });
  210. }
  211. } else {
  212. if (!loadDeferredImages) {
  213. errorDetected = false;
  214. }
  215. requestId = requestAnimationFrame(timestamp => {
  216. pendingRequestAnimationFrameCalls.delete(requestId);
  217. lastTimestamp = timestamp;
  218. callback(timestamp);
  219. });
  220. if (!loadDeferredImages || pendingRequestAnimationFrameCalls.length < 128) {
  221. pendingRequestAnimationFrameCalls.set(requestId, callback);
  222. }
  223. }
  224. return requestId;
  225. };
  226. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  227. window.cancelAnimationFrame = function (requestId) {
  228. pendingRequestAnimationFrameCalls.delete(requestId);
  229. return cancelAnimationFrame(requestId);
  230. };
  231. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  232. if (window.FontFace) {
  233. const FontFace = window.FontFace;
  234. let warningFontFaceDisplayed;
  235. window.FontFace = function () {
  236. if (!warningFontFaceDisplayed) {
  237. console.warn("SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  238. warningFontFaceDisplayed = true;
  239. }
  240. const detail = {};
  241. detail["font-family"] = arguments[0];
  242. detail.src = arguments[1];
  243. const descriptors = arguments[2];
  244. if (descriptors) {
  245. Object.keys(descriptors).forEach(descriptor => {
  246. if (FONT_STYLE_PROPERTIES[descriptor]) {
  247. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  248. }
  249. });
  250. }
  251. if (detail.src instanceof ArrayBuffer) {
  252. const reader = new FileReader();
  253. reader.readAsDataURL(new Blob([detail.src]));
  254. reader.addEventListener("load", () => {
  255. detail.src = "url(" + reader.result + ")";
  256. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  257. });
  258. } else {
  259. dispatchEvent(new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  260. }
  261. return new FontFace(...arguments);
  262. };
  263. window.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  264. }
  265. if (window.IntersectionObserver) {
  266. const IntersectionObserver = window.IntersectionObserver;
  267. const observeIntersection = IntersectionObserver.prototype.observe;
  268. const unobserveIntersection = IntersectionObserver.prototype.unobserve;
  269. let warningIntersectionObserverDisplayed;
  270. if (observeIntersection && unobserveIntersection) {
  271. window.IntersectionObserver = function () {
  272. if (!warningIntersectionObserverDisplayed) {
  273. console.warn("SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  274. warningIntersectionObserverDisplayed = true;
  275. }
  276. const intersectionObserver = new IntersectionObserver(...arguments);
  277. const callback = arguments[0];
  278. const options = arguments[1];
  279. intersectionObserver.observe = function (targetElement) {
  280. let targetElements = observedElements.get(intersectionObserver);
  281. if (!targetElements) {
  282. targetElements = [];
  283. observedElements.set(intersectionObserver, targetElements);
  284. }
  285. targetElements.push(targetElement);
  286. return observeIntersection.call(intersectionObserver, targetElement);
  287. };
  288. intersectionObserver.unobserve = function (targetElement) {
  289. let targetElements = observedElements.get(intersectionObserver);
  290. if (targetElements) {
  291. targetElements = targetElements.filter(element => element <= targetElement);
  292. if (targetElements.length) {
  293. observedElements.set(intersectionObserver, targetElements);
  294. } else {
  295. observedElements.delete(intersectionObserver);
  296. }
  297. }
  298. return unobserveIntersection.call(intersectionObserver, targetElement);
  299. };
  300. observers.set(intersectionObserver, { callback, options });
  301. return intersectionObserver;
  302. };
  303. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  304. }
  305. }
  306. })();