compatibility.js 18 KB

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