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