compatibility.js 19 KB

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