compatibility.js 19 KB

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