2
0

compatibility.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. } else {
  185. return this.responseText;
  186. }
  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) { return fn(msg); };
  385. })(console.log);
  386. console.error = (function(fn) {
  387. return function(msg) { return fn(msg); };
  388. })(console.error);
  389. console.warn = (function(fn) {
  390. return function(msg) { return fn(msg); };
  391. })(console.warn);
  392. }
  393. })();
  394. // Check onclick compatibility in Opera
  395. // Support: Opera<15
  396. (function checkOnClickCompatibility() {
  397. // workaround for reported Opera bug DSK-354448:
  398. // onclick fires on disabled buttons with opaque content
  399. function ignoreIfTargetDisabled(event) {
  400. if (isDisabled(event.target)) {
  401. event.stopPropagation();
  402. }
  403. }
  404. function isDisabled(node) {
  405. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  406. }
  407. if (isOpera) {
  408. // use browser detection since we cannot feature-check this bug
  409. document.addEventListener('click', ignoreIfTargetDisabled, true);
  410. }
  411. })();
  412. // Checks if possible to use URL.createObjectURL()
  413. // Support: IE
  414. (function checkOnBlobSupport() {
  415. // sometimes IE loosing the data created with createObjectURL(), see #3977
  416. if (isIE) {
  417. PDFJS.disableCreateObjectURL = true;
  418. }
  419. })();
  420. // Checks if navigator.language is supported
  421. (function checkNavigatorLanguage() {
  422. if ('language' in navigator) {
  423. return;
  424. }
  425. PDFJS.locale = navigator.userLanguage || 'en-US';
  426. })();
  427. // Support: Safari 6.0+, Android<3.0, Chrome 39/40, iOS
  428. (function checkRangeRequests() {
  429. // Safari has issues with cached range requests see:
  430. // https://github.com/mozilla/pdf.js/issues/3260
  431. // Last tested with version 6.0.4.
  432. // Older versions of Android (pre 3.0) has issues with range requests, see:
  433. // https://github.com/mozilla/pdf.js/issues/3381.
  434. // Make sure that we only match webkit-based Android browsers,
  435. // since Firefox/Fennec works as expected.
  436. // Range requests are broken in Chrome 39 and 40, https://crbug.com/442318
  437. if (isSafari || isAndroidPre3 || isChromeWithRangeBug || isIOS) {
  438. PDFJS.disableRange = true;
  439. PDFJS.disableStream = true;
  440. }
  441. })();
  442. // Check if the browser supports manipulation of the history.
  443. // Support: IE<10, Android<4.2
  444. (function checkHistoryManipulation() {
  445. // Android 2.x has so buggy pushState support that it was removed in
  446. // Android 3.0 and restored as late as in Android 4.2.
  447. // Support: Android 2.x
  448. if (!history.pushState || isAndroidPre3) {
  449. PDFJS.disableHistory = true;
  450. }
  451. })();
  452. // Support: IE<11, Chrome<21, Android<4.4, Safari<6
  453. (function checkSetPresenceInImageData() {
  454. // IE < 11 will use window.CanvasPixelArray which lacks set function.
  455. if (window.CanvasPixelArray) {
  456. if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
  457. window.CanvasPixelArray.prototype.set = function(arr) {
  458. for (var i = 0, ii = this.length; i < ii; i++) {
  459. this[i] = arr[i];
  460. }
  461. };
  462. }
  463. } else {
  464. // Old Chrome and Android use an inaccessible CanvasPixelArray prototype.
  465. // Because we cannot feature detect it, we rely on user agent parsing.
  466. var polyfill = false, versionMatch;
  467. if (isChrome) {
  468. versionMatch = userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  469. // Chrome < 21 lacks the set function.
  470. polyfill = versionMatch && parseInt(versionMatch[2]) < 21;
  471. } else if (isAndroid) {
  472. // Android < 4.4 lacks the set function.
  473. // Android >= 4.4 will contain Chrome in the user agent,
  474. // thus pass the Chrome check above and not reach this block.
  475. polyfill = isAndroidPre5;
  476. } else if (isSafari) {
  477. versionMatch = userAgent.
  478. match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//);
  479. // Safari < 6 lacks the set function.
  480. polyfill = versionMatch && parseInt(versionMatch[1]) < 6;
  481. }
  482. if (polyfill) {
  483. var contextPrototype = window.CanvasRenderingContext2D.prototype;
  484. var createImageData = contextPrototype.createImageData;
  485. contextPrototype.createImageData = function(w, h) {
  486. var imageData = createImageData.call(this, w, h);
  487. imageData.data.set = function(arr) {
  488. for (var i = 0, ii = this.length; i < ii; i++) {
  489. this[i] = arr[i];
  490. }
  491. };
  492. return imageData;
  493. };
  494. // this closure will be kept referenced, so clear its vars
  495. contextPrototype = null;
  496. }
  497. }
  498. })();
  499. // Support: IE<10, Android<4.0, iOS
  500. (function checkRequestAnimationFrame() {
  501. function fakeRequestAnimationFrame(callback) {
  502. window.setTimeout(callback, 20);
  503. }
  504. if (isIOS) {
  505. // requestAnimationFrame on iOS is broken, replacing with fake one.
  506. window.requestAnimationFrame = fakeRequestAnimationFrame;
  507. return;
  508. }
  509. if ('requestAnimationFrame' in window) {
  510. return;
  511. }
  512. window.requestAnimationFrame =
  513. window.mozRequestAnimationFrame ||
  514. window.webkitRequestAnimationFrame ||
  515. fakeRequestAnimationFrame;
  516. })();
  517. // Support: Android, iOS
  518. (function checkCanvasSizeLimitation() {
  519. if (isIOS || isAndroid) {
  520. // 5MP
  521. PDFJS.maxCanvasPixels = 5242880;
  522. }
  523. })();
  524. // Disable fullscreen support for certain problematic configurations.
  525. // Support: IE11+ (when embedded).
  526. (function checkFullscreenSupport() {
  527. if (isIE && window.parent !== window) {
  528. PDFJS.disableFullscreen = true;
  529. }
  530. })();
  531. // Provides document.currentScript support
  532. // Support: IE, Chrome<29.
  533. (function checkCurrentScript() {
  534. if ('currentScript' in document) {
  535. return;
  536. }
  537. Object.defineProperty(document, 'currentScript', {
  538. get: function () {
  539. var scripts = document.getElementsByTagName('script');
  540. return scripts[scripts.length - 1];
  541. },
  542. enumerable: true,
  543. configurable: true
  544. });
  545. })();
  546. }).call((typeof window === 'undefined') ? this : window);