2
0

compatibility.js 18 KB

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