compatibility.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* globals VBArray, PDFJS */
  18. 'use strict';
  19. // Initializing PDFJS global object here, it case if we need to change/disable
  20. // some PDF.js features, e.g. range requests
  21. if (typeof PDFJS === 'undefined') {
  22. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  23. }
  24. // Checking if the typed arrays are supported
  25. // Support: iOS<6.0 (subarray), IE<10, Android<4.0
  26. (function checkTypedArrayCompatibility() {
  27. if (typeof Uint8Array !== 'undefined') {
  28. // Support: iOS<6.0
  29. if (typeof Uint8Array.prototype.subarray === 'undefined') {
  30. Uint8Array.prototype.subarray = function subarray(start, end) {
  31. return new Uint8Array(this.slice(start, end));
  32. };
  33. Float32Array.prototype.subarray = function subarray(start, end) {
  34. return new Float32Array(this.slice(start, end));
  35. };
  36. }
  37. // Support: Android<4.1
  38. if (typeof Float64Array === 'undefined') {
  39. window.Float64Array = Float32Array;
  40. }
  41. return;
  42. }
  43. function subarray(start, end) {
  44. return new TypedArray(this.slice(start, end));
  45. }
  46. function setArrayOffset(array, offset) {
  47. if (arguments.length < 2) {
  48. offset = 0;
  49. }
  50. for (var i = 0, n = array.length; i < n; ++i, ++offset) {
  51. this[offset] = array[i] & 0xFF;
  52. }
  53. }
  54. function TypedArray(arg1) {
  55. var result, i, n;
  56. if (typeof arg1 === 'number') {
  57. result = [];
  58. for (i = 0; i < arg1; ++i) {
  59. result[i] = 0;
  60. }
  61. } else if ('slice' in arg1) {
  62. result = arg1.slice(0);
  63. } else {
  64. result = [];
  65. for (i = 0, n = arg1.length; i < n; ++i) {
  66. result[i] = arg1[i];
  67. }
  68. }
  69. result.subarray = subarray;
  70. result.buffer = result;
  71. result.byteLength = result.length;
  72. result.set = setArrayOffset;
  73. if (typeof arg1 === 'object' && arg1.buffer) {
  74. result.buffer = arg1.buffer;
  75. }
  76. return result;
  77. }
  78. window.Uint8Array = TypedArray;
  79. window.Int8Array = TypedArray;
  80. // we don't need support for set, byteLength for 32-bit array
  81. // so we can use the TypedArray as well
  82. window.Uint32Array = TypedArray;
  83. window.Int32Array = TypedArray;
  84. window.Uint16Array = TypedArray;
  85. window.Float32Array = TypedArray;
  86. window.Float64Array = TypedArray;
  87. })();
  88. // URL = URL || webkitURL
  89. // Support: Safari<7, Android 4.2+
  90. (function normalizeURLObject() {
  91. if (!window.URL) {
  92. window.URL = window.webkitURL;
  93. }
  94. })();
  95. // Object.defineProperty()?
  96. // Support: Android<4.0, Safari<5.1
  97. (function checkObjectDefinePropertyCompatibility() {
  98. if (typeof Object.defineProperty !== 'undefined') {
  99. var definePropertyPossible = true;
  100. try {
  101. // some browsers (e.g. safari) cannot use defineProperty() on DOM objects
  102. // and thus the native version is not sufficient
  103. Object.defineProperty(new Image(), 'id', {value: 'test'});
  104. // ... another test for android gb browser for non-DOM objects
  105. var Test = function Test() {
  106. };
  107. Test.prototype = {
  108. get id() {
  109. }
  110. };
  111. Object.defineProperty(new Test(), 'id',
  112. {value: '', configurable: true, enumerable: true, writable: false});
  113. } catch (e) {
  114. definePropertyPossible = false;
  115. }
  116. if (definePropertyPossible) {
  117. return;
  118. }
  119. }
  120. Object.defineProperty = function objectDefineProperty(obj, name, def) {
  121. delete obj[name];
  122. if ('get' in def) {
  123. obj.__defineGetter__(name, def['get']);
  124. }
  125. if ('set' in def) {
  126. obj.__defineSetter__(name, def['set']);
  127. }
  128. if ('value' in def) {
  129. obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
  130. this.__defineGetter__(name, function objectDefinePropertyGetter() {
  131. return value;
  132. });
  133. return value;
  134. });
  135. obj[name] = def.value;
  136. }
  137. };
  138. })();
  139. // No XMLHttpRequest#response?
  140. // Support: IE<11, Android <4.0
  141. (function checkXMLHttpRequestResponseCompatibility() {
  142. var xhrPrototype = XMLHttpRequest.prototype;
  143. var xhr = new XMLHttpRequest();
  144. if (!('overrideMimeType' in xhr)) {
  145. // IE10 might have response, but not overrideMimeType
  146. // Support: IE10
  147. Object.defineProperty(xhrPrototype, 'overrideMimeType', {
  148. value: function xmlHttpRequestOverrideMimeType(mimeType) {
  149. }
  150. });
  151. }
  152. if ('responseType' in xhr) {
  153. return;
  154. }
  155. // The worker will be using XHR, so we can save time and disable worker.
  156. PDFJS.disableWorker = true;
  157. Object.defineProperty(xhrPrototype, 'responseType', {
  158. get: function xmlHttpRequestGetResponseType() {
  159. return this._responseType || 'text';
  160. },
  161. set: function xmlHttpRequestSetResponseType(value) {
  162. if (value === 'text' || value === 'arraybuffer') {
  163. this._responseType = value;
  164. if (value === 'arraybuffer' &&
  165. typeof this.overrideMimeType === 'function') {
  166. this.overrideMimeType('text/plain; charset=x-user-defined');
  167. }
  168. }
  169. }
  170. });
  171. // Support: IE9
  172. if (typeof VBArray !== 'undefined') {
  173. Object.defineProperty(xhrPrototype, 'response', {
  174. get: function xmlHttpRequestResponseGet() {
  175. if (this.responseType === 'arraybuffer') {
  176. return new Uint8Array(new VBArray(this.responseBody).toArray());
  177. } else {
  178. return this.responseText;
  179. }
  180. }
  181. });
  182. return;
  183. }
  184. Object.defineProperty(xhrPrototype, 'response', {
  185. get: function xmlHttpRequestResponseGet() {
  186. if (this.responseType !== 'arraybuffer') {
  187. return this.responseText;
  188. }
  189. var text = this.responseText;
  190. var i, n = text.length;
  191. var result = new Uint8Array(n);
  192. for (i = 0; i < n; ++i) {
  193. result[i] = text.charCodeAt(i) & 0xFF;
  194. }
  195. return result.buffer;
  196. }
  197. });
  198. })();
  199. // window.btoa (base64 encode function) ?
  200. // Support: IE<10
  201. (function checkWindowBtoaCompatibility() {
  202. if ('btoa' in window) {
  203. return;
  204. }
  205. var digits =
  206. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  207. window.btoa = function windowBtoa(chars) {
  208. var buffer = '';
  209. var i, n;
  210. for (i = 0, n = chars.length; i < n; i += 3) {
  211. var b1 = chars.charCodeAt(i) & 0xFF;
  212. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  213. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  214. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  215. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  216. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  217. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  218. digits.charAt(d3) + digits.charAt(d4));
  219. }
  220. return buffer;
  221. };
  222. })();
  223. // window.atob (base64 encode function)?
  224. // Support: IE<10
  225. (function checkWindowAtobCompatibility() {
  226. if ('atob' in window) {
  227. return;
  228. }
  229. // https://github.com/davidchambers/Base64.js
  230. var digits =
  231. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  232. window.atob = function (input) {
  233. input = input.replace(/=+$/, '');
  234. if (input.length % 4 === 1) {
  235. throw new Error('bad atob input');
  236. }
  237. for (
  238. // initialize result and counters
  239. var bc = 0, bs, buffer, idx = 0, output = '';
  240. // get next character
  241. buffer = input.charAt(idx++);
  242. // character found in table?
  243. // initialize bit storage and add its ascii value
  244. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  245. // and if not first of each 4 characters,
  246. // convert the first 8 bits to one ascii character
  247. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  248. ) {
  249. // try to find character in table (0-63, not found => -1)
  250. buffer = digits.indexOf(buffer);
  251. }
  252. return output;
  253. };
  254. })();
  255. // Function.prototype.bind?
  256. // Support: Android<4.0, iOS<6.0
  257. (function checkFunctionPrototypeBindCompatibility() {
  258. if (typeof Function.prototype.bind !== 'undefined') {
  259. return;
  260. }
  261. Function.prototype.bind = function functionPrototypeBind(obj) {
  262. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  263. var bound = function functionPrototypeBindBound() {
  264. var args = headArgs.concat(Array.prototype.slice.call(arguments));
  265. return fn.apply(obj, args);
  266. };
  267. return bound;
  268. };
  269. })();
  270. // HTMLElement dataset property
  271. // Support: IE<11, Safari<5.1, Android<4.0
  272. (function checkDatasetProperty() {
  273. var div = document.createElement('div');
  274. if ('dataset' in div) {
  275. return; // dataset property exists
  276. }
  277. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  278. get: function () {
  279. if (this._dataset) {
  280. return this._dataset;
  281. }
  282. var dataset = {};
  283. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  284. var attribute = this.attributes[j];
  285. if (attribute.name.substring(0, 5) !== 'data-') {
  286. continue;
  287. }
  288. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  289. function (all, ch) {
  290. return ch.toUpperCase();
  291. });
  292. dataset[key] = attribute.value;
  293. }
  294. Object.defineProperty(this, '_dataset', {
  295. value: dataset,
  296. writable: false,
  297. enumerable: false
  298. });
  299. return dataset;
  300. },
  301. enumerable: true
  302. });
  303. })();
  304. // HTMLElement classList property
  305. // Support: IE<10, Android<4.0, iOS<5.0
  306. (function checkClassListProperty() {
  307. var div = document.createElement('div');
  308. if ('classList' in div) {
  309. return; // classList property exists
  310. }
  311. function changeList(element, itemName, add, remove) {
  312. var s = element.className || '';
  313. var list = s.split(/\s+/g);
  314. if (list[0] === '') {
  315. list.shift();
  316. }
  317. var index = list.indexOf(itemName);
  318. if (index < 0 && add) {
  319. list.push(itemName);
  320. }
  321. if (index >= 0 && remove) {
  322. list.splice(index, 1);
  323. }
  324. element.className = list.join(' ');
  325. return (index >= 0);
  326. }
  327. var classListPrototype = {
  328. add: function (name) {
  329. changeList(this.element, name, true, false);
  330. },
  331. contains: function (name) {
  332. return changeList(this.element, name, false, false);
  333. },
  334. remove: function (name) {
  335. changeList(this.element, name, false, true);
  336. },
  337. toggle: function (name) {
  338. changeList(this.element, name, true, true);
  339. }
  340. };
  341. Object.defineProperty(HTMLElement.prototype, 'classList', {
  342. get: function () {
  343. if (this._classList) {
  344. return this._classList;
  345. }
  346. var classList = Object.create(classListPrototype, {
  347. element: {
  348. value: this,
  349. writable: false,
  350. enumerable: true
  351. }
  352. });
  353. Object.defineProperty(this, '_classList', {
  354. value: classList,
  355. writable: false,
  356. enumerable: false
  357. });
  358. return classList;
  359. },
  360. enumerable: true
  361. });
  362. })();
  363. // Check console compatibility
  364. // In older IE versions the console object is not available
  365. // unless console is open.
  366. // Support: IE<10
  367. (function checkConsoleCompatibility() {
  368. if (!('console' in window)) {
  369. window.console = {
  370. log: function () {
  371. },
  372. error: function () {
  373. },
  374. warn: function () {
  375. }
  376. };
  377. } else if (!('bind' in console.log)) {
  378. // native functions in IE9 might not have bind
  379. console.log = (function (fn) {
  380. return function (msg) {
  381. return fn(msg);
  382. };
  383. })(console.log);
  384. console.error = (function (fn) {
  385. return function (msg) {
  386. return fn(msg);
  387. };
  388. })(console.error);
  389. console.warn = (function (fn) {
  390. return function (msg) {
  391. return fn(msg);
  392. };
  393. })(console.warn);
  394. }
  395. })();
  396. // Check onclick compatibility in Opera
  397. // Support: Opera<15
  398. (function checkOnClickCompatibility() {
  399. // workaround for reported Opera bug DSK-354448:
  400. // onclick fires on disabled buttons with opaque content
  401. function ignoreIfTargetDisabled(event) {
  402. if (isDisabled(event.target)) {
  403. event.stopPropagation();
  404. }
  405. }
  406. function isDisabled(node) {
  407. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  408. }
  409. if (navigator.userAgent.indexOf('Opera') !== -1) {
  410. // use browser detection since we cannot feature-check this bug
  411. document.addEventListener('click', ignoreIfTargetDisabled, true);
  412. }
  413. })();
  414. // Checks if possible to use URL.createObjectURL()
  415. // Support: IE
  416. (function checkOnBlobSupport() {
  417. // sometimes IE loosing the data created with createObjectURL(), see #3977
  418. if (navigator.userAgent.indexOf('Trident') >= 0) {
  419. PDFJS.disableCreateObjectURL = true;
  420. }
  421. })();
  422. // Checks if navigator.language is supported
  423. (function checkNavigatorLanguage() {
  424. if ('language' in navigator) {
  425. return;
  426. }
  427. PDFJS.locale = navigator.userLanguage || 'en-US';
  428. })();
  429. (function checkRangeRequests() {
  430. // Safari has issues with cached range requests see:
  431. // https://github.com/mozilla/pdf.js/issues/3260
  432. // Last tested with version 6.0.4.
  433. // Support: Safari 6.0+
  434. var isSafari = Object.prototype.toString.call(
  435. window.HTMLElement).indexOf('Constructor') > 0;
  436. // Older versions of Android (pre 3.0) has issues with range requests, see:
  437. // https://github.com/mozilla/pdf.js/issues/3381.
  438. // Make sure that we only match webkit-based Android browsers,
  439. // since Firefox/Fennec works as expected.
  440. // Support: Android<3.0
  441. var regex = /Android\s[0-2][^\d]/;
  442. var isOldAndroid = regex.test(navigator.userAgent);
  443. // Range requests are broken in Chrome 39 and 40, https://crbug.com/442318
  444. var isChromeWithRangeBug = /Chrome\/(39|40)\./.test(navigator.userAgent);
  445. if (isSafari || isOldAndroid || isChromeWithRangeBug) {
  446. PDFJS.disableRange = true;
  447. PDFJS.disableStream = true;
  448. }
  449. })();
  450. // Check if the browser supports manipulation of the history.
  451. // Support: IE<10, Android<4.2
  452. (function checkHistoryManipulation() {
  453. // Android 2.x has so buggy pushState support that it was removed in
  454. // Android 3.0 and restored as late as in Android 4.2.
  455. // Support: Android 2.x
  456. if (!history.pushState || navigator.userAgent.indexOf('Android 2.') >= 0) {
  457. PDFJS.disableHistory = true;
  458. }
  459. })();
  460. // Support: IE<11, Chrome<21, Android<4.4, Safari<6
  461. (function checkSetPresenceInImageData() {
  462. // IE < 11 will use window.CanvasPixelArray which lacks set function.
  463. if (window.CanvasPixelArray) {
  464. if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
  465. window.CanvasPixelArray.prototype.set = function (arr) {
  466. for (var i = 0, ii = this.length; i < ii; i++) {
  467. this[i] = arr[i];
  468. }
  469. };
  470. }
  471. } else {
  472. // Old Chrome and Android use an inaccessible CanvasPixelArray prototype.
  473. // Because we cannot feature detect it, we rely on user agent parsing.
  474. var polyfill = false, versionMatch;
  475. if (navigator.userAgent.indexOf('Chrom') >= 0) {
  476. versionMatch = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  477. // Chrome < 21 lacks the set function.
  478. polyfill = versionMatch && parseInt(versionMatch[2]) < 21;
  479. } else if (navigator.userAgent.indexOf('Android') >= 0) {
  480. // Android < 4.4 lacks the set function.
  481. // Android >= 4.4 will contain Chrome in the user agent,
  482. // thus pass the Chrome check above and not reach this block.
  483. polyfill = /Android\s[0-4][^\d]/g.test(navigator.userAgent);
  484. } else if (navigator.userAgent.indexOf('Safari') >= 0) {
  485. versionMatch = navigator.userAgent.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//);
  486. // Safari < 6 lacks the set function.
  487. polyfill = versionMatch && parseInt(versionMatch[1]) < 6;
  488. }
  489. if (polyfill) {
  490. var contextPrototype = window.CanvasRenderingContext2D.prototype;
  491. contextPrototype._createImageData = contextPrototype.createImageData;
  492. contextPrototype.createImageData = function (w, h) {
  493. var imageData = this._createImageData(w, h);
  494. imageData.data.set = function (arr) {
  495. for (var i = 0, ii = this.length; i < ii; i++) {
  496. this[i] = arr[i];
  497. }
  498. };
  499. return imageData;
  500. };
  501. }
  502. }
  503. })();
  504. // Support: IE<10, Android<4.0, iOS
  505. (function checkRequestAnimationFrame() {
  506. function fakeRequestAnimationFrame(callback) {
  507. window.setTimeout(callback, 20);
  508. }
  509. var isIOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  510. if (isIOS) {
  511. // requestAnimationFrame on iOS is broken, replacing with fake one.
  512. window.requestAnimationFrame = fakeRequestAnimationFrame;
  513. return;
  514. }
  515. if ('requestAnimationFrame' in window) {
  516. return;
  517. }
  518. window.requestAnimationFrame =
  519. window.mozRequestAnimationFrame ||
  520. window.webkitRequestAnimationFrame ||
  521. fakeRequestAnimationFrame;
  522. })();
  523. (function checkCanvasSizeLimitation() {
  524. var isIOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  525. var isAndroid = /Android/g.test(navigator.userAgent);
  526. if (isIOS || isAndroid) {
  527. // 5MP
  528. PDFJS.maxCanvasPixels = 5242880;
  529. }
  530. })();
  531. // Disable fullscreen support for certain problematic configurations.
  532. // Support: IE11+ (when embedded).
  533. (function checkFullscreenSupport() {
  534. var isEmbeddedIE = (navigator.userAgent.indexOf('Trident') >= 0 &&
  535. window.parent !== window);
  536. if (isEmbeddedIE) {
  537. PDFJS.disableFullscreen = true;
  538. }
  539. })();