compatibility.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* globals VBArray, PDFJS */
  18. 'use strict';
  19. // Initializing PDFJS global object here, it case if we need to change/disable
  20. // some PDF.js features, e.g. range requests
  21. if (typeof PDFJS === 'undefined') {
  22. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  23. }
  24. // Checking if the typed arrays are supported
  25. // Support: iOS<6.0 (subarray), IE<10, Android<4.0
  26. (function checkTypedArrayCompatibility() {
  27. if (typeof Uint8Array !== 'undefined') {
  28. // Support: iOS<6.0
  29. if (typeof Uint8Array.prototype.subarray === 'undefined') {
  30. Uint8Array.prototype.subarray = function subarray(start, end) {
  31. return new Uint8Array(this.slice(start, end));
  32. };
  33. Float32Array.prototype.subarray = function subarray(start, end) {
  34. return new Float32Array(this.slice(start, end));
  35. };
  36. }
  37. // Support: Android<4.1
  38. if (typeof Float64Array === 'undefined') {
  39. window.Float64Array = Float32Array;
  40. }
  41. return;
  42. }
  43. function subarray(start, end) {
  44. return new TypedArray(this.slice(start, end));
  45. }
  46. function setArrayOffset(array, offset) {
  47. if (arguments.length < 2) {
  48. offset = 0;
  49. }
  50. for (var i = 0, n = array.length; i < n; ++i, ++offset) {
  51. this[offset] = array[i] & 0xFF;
  52. }
  53. }
  54. function TypedArray(arg1) {
  55. var result, i, n;
  56. if (typeof arg1 === 'number') {
  57. result = [];
  58. for (i = 0; i < arg1; ++i) {
  59. result[i] = 0;
  60. }
  61. } else if ('slice' in arg1) {
  62. result = arg1.slice(0);
  63. } else {
  64. result = [];
  65. for (i = 0, n = arg1.length; i < n; ++i) {
  66. result[i] = arg1[i];
  67. }
  68. }
  69. result.subarray = subarray;
  70. result.buffer = result;
  71. result.byteLength = result.length;
  72. result.set = setArrayOffset;
  73. if (typeof arg1 === 'object' && arg1.buffer) {
  74. result.buffer = arg1.buffer;
  75. }
  76. return result;
  77. }
  78. window.Uint8Array = TypedArray;
  79. window.Int8Array = TypedArray;
  80. // we don't need support for set, byteLength for 32-bit array
  81. // so we can use the TypedArray as well
  82. window.Uint32Array = TypedArray;
  83. window.Int32Array = TypedArray;
  84. window.Uint16Array = TypedArray;
  85. window.Float32Array = TypedArray;
  86. window.Float64Array = TypedArray;
  87. })();
  88. // URL = URL || webkitURL
  89. // Support: Safari<7, Android 4.2+
  90. (function normalizeURLObject() {
  91. if (!window.URL) {
  92. window.URL = window.webkitURL;
  93. }
  94. })();
  95. // Object.defineProperty()?
  96. // Support: Android<4.0, Safari<5.1
  97. (function checkObjectDefinePropertyCompatibility() {
  98. if (typeof Object.defineProperty !== 'undefined') {
  99. var definePropertyPossible = true;
  100. try {
  101. // some browsers (e.g. safari) cannot use defineProperty() on DOM objects
  102. // and thus the native version is not sufficient
  103. Object.defineProperty(new Image(), 'id', { value: 'test' });
  104. // ... another test for android gb browser for non-DOM objects
  105. var Test = function Test() {};
  106. Test.prototype = { get id() { } };
  107. Object.defineProperty(new Test(), 'id',
  108. { value: '', configurable: true, enumerable: true, writable: false });
  109. } catch (e) {
  110. definePropertyPossible = false;
  111. }
  112. if (definePropertyPossible) {
  113. return;
  114. }
  115. }
  116. Object.defineProperty = function objectDefineProperty(obj, name, def) {
  117. delete obj[name];
  118. if ('get' in def) {
  119. obj.__defineGetter__(name, def['get']);
  120. }
  121. if ('set' in def) {
  122. obj.__defineSetter__(name, def['set']);
  123. }
  124. if ('value' in def) {
  125. obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
  126. this.__defineGetter__(name, function objectDefinePropertyGetter() {
  127. return value;
  128. });
  129. return value;
  130. });
  131. obj[name] = def.value;
  132. }
  133. };
  134. })();
  135. // No XMLHttpRequest#response?
  136. // Support: IE<11, Android <4.0
  137. (function checkXMLHttpRequestResponseCompatibility() {
  138. var xhrPrototype = XMLHttpRequest.prototype;
  139. var xhr = new XMLHttpRequest();
  140. if (!('overrideMimeType' in xhr)) {
  141. // IE10 might have response, but not overrideMimeType
  142. // Support: IE10
  143. Object.defineProperty(xhrPrototype, 'overrideMimeType', {
  144. value: function xmlHttpRequestOverrideMimeType(mimeType) {}
  145. });
  146. }
  147. if ('responseType' in xhr) {
  148. return;
  149. }
  150. // The worker will be using XHR, so we can save time and disable worker.
  151. PDFJS.disableWorker = true;
  152. // Support: IE9
  153. if (typeof VBArray !== 'undefined') {
  154. Object.defineProperty(xhrPrototype, 'response', {
  155. get: function xmlHttpRequestResponseGet() {
  156. if (this.responseType === 'arraybuffer') {
  157. return new Uint8Array(new VBArray(this.responseBody).toArray());
  158. } else {
  159. return this.responseText;
  160. }
  161. }
  162. });
  163. return;
  164. }
  165. // other browsers
  166. function responseTypeSetter() {
  167. // will be only called to set "arraybuffer"
  168. this.overrideMimeType('text/plain; charset=x-user-defined');
  169. }
  170. if (typeof xhr.overrideMimeType === 'function') {
  171. Object.defineProperty(xhrPrototype, 'responseType',
  172. { set: responseTypeSetter });
  173. }
  174. function responseGetter() {
  175. var text = this.responseText;
  176. var i, n = text.length;
  177. var result = new Uint8Array(n);
  178. for (i = 0; i < n; ++i) {
  179. result[i] = text.charCodeAt(i) & 0xFF;
  180. }
  181. return result.buffer;
  182. }
  183. Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
  184. })();
  185. // window.btoa (base64 encode function) ?
  186. // Support: IE<10
  187. (function checkWindowBtoaCompatibility() {
  188. if ('btoa' in window) {
  189. return;
  190. }
  191. var digits =
  192. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  193. window.btoa = function windowBtoa(chars) {
  194. var buffer = '';
  195. var i, n;
  196. for (i = 0, n = chars.length; i < n; i += 3) {
  197. var b1 = chars.charCodeAt(i) & 0xFF;
  198. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  199. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  200. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  201. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  202. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  203. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  204. digits.charAt(d3) + digits.charAt(d4));
  205. }
  206. return buffer;
  207. };
  208. })();
  209. // window.atob (base64 encode function)?
  210. // Support: IE<10
  211. (function checkWindowAtobCompatibility() {
  212. if ('atob' in window) {
  213. return;
  214. }
  215. // https://github.com/davidchambers/Base64.js
  216. var digits =
  217. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  218. window.atob = function (input) {
  219. input = input.replace(/=+$/, '');
  220. if (input.length % 4 === 1) {
  221. throw new Error('bad atob input');
  222. }
  223. for (
  224. // initialize result and counters
  225. var bc = 0, bs, buffer, idx = 0, output = '';
  226. // get next character
  227. buffer = input.charAt(idx++);
  228. // character found in table?
  229. // initialize bit storage and add its ascii value
  230. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  231. // and if not first of each 4 characters,
  232. // convert the first 8 bits to one ascii character
  233. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  234. ) {
  235. // try to find character in table (0-63, not found => -1)
  236. buffer = digits.indexOf(buffer);
  237. }
  238. return output;
  239. };
  240. })();
  241. // Function.prototype.bind?
  242. // Support: Android<4.0, iOS<6.0
  243. (function checkFunctionPrototypeBindCompatibility() {
  244. if (typeof Function.prototype.bind !== 'undefined') {
  245. return;
  246. }
  247. Function.prototype.bind = function functionPrototypeBind(obj) {
  248. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  249. var bound = function functionPrototypeBindBound() {
  250. var args = headArgs.concat(Array.prototype.slice.call(arguments));
  251. return fn.apply(obj, args);
  252. };
  253. return bound;
  254. };
  255. })();
  256. // HTMLElement dataset property
  257. // Support: IE<11, Safari<5.1, Android<4.0
  258. (function checkDatasetProperty() {
  259. var div = document.createElement('div');
  260. if ('dataset' in div) {
  261. return; // dataset property exists
  262. }
  263. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  264. get: function() {
  265. if (this._dataset) {
  266. return this._dataset;
  267. }
  268. var dataset = {};
  269. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  270. var attribute = this.attributes[j];
  271. if (attribute.name.substring(0, 5) !== 'data-') {
  272. continue;
  273. }
  274. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  275. function(all, ch) {
  276. return ch.toUpperCase();
  277. });
  278. dataset[key] = attribute.value;
  279. }
  280. Object.defineProperty(this, '_dataset', {
  281. value: dataset,
  282. writable: false,
  283. enumerable: false
  284. });
  285. return dataset;
  286. },
  287. enumerable: true
  288. });
  289. })();
  290. // HTMLElement classList property
  291. // Support: IE<10, Android<4.0, iOS<5.0
  292. (function checkClassListProperty() {
  293. var div = document.createElement('div');
  294. if ('classList' in div) {
  295. return; // classList property exists
  296. }
  297. function changeList(element, itemName, add, remove) {
  298. var s = element.className || '';
  299. var list = s.split(/\s+/g);
  300. if (list[0] === '') {
  301. list.shift();
  302. }
  303. var index = list.indexOf(itemName);
  304. if (index < 0 && add) {
  305. list.push(itemName);
  306. }
  307. if (index >= 0 && remove) {
  308. list.splice(index, 1);
  309. }
  310. element.className = list.join(' ');
  311. return (index >= 0);
  312. }
  313. var classListPrototype = {
  314. add: function(name) {
  315. changeList(this.element, name, true, false);
  316. },
  317. contains: function(name) {
  318. return changeList(this.element, name, false, false);
  319. },
  320. remove: function(name) {
  321. changeList(this.element, name, false, true);
  322. },
  323. toggle: function(name) {
  324. changeList(this.element, name, true, true);
  325. }
  326. };
  327. Object.defineProperty(HTMLElement.prototype, 'classList', {
  328. get: function() {
  329. if (this._classList) {
  330. return this._classList;
  331. }
  332. var classList = Object.create(classListPrototype, {
  333. element: {
  334. value: this,
  335. writable: false,
  336. enumerable: true
  337. }
  338. });
  339. Object.defineProperty(this, '_classList', {
  340. value: classList,
  341. writable: false,
  342. enumerable: false
  343. });
  344. return classList;
  345. },
  346. enumerable: true
  347. });
  348. })();
  349. // Check console compatibility
  350. // In older IE versions the console object is not available
  351. // unless console is open.
  352. // Support: IE<10
  353. (function checkConsoleCompatibility() {
  354. if (!('console' in window)) {
  355. window.console = {
  356. log: function() {},
  357. error: function() {},
  358. warn: function() {}
  359. };
  360. } else if (!('bind' in console.log)) {
  361. // native functions in IE9 might not have bind
  362. console.log = (function(fn) {
  363. return function(msg) { return fn(msg); };
  364. })(console.log);
  365. console.error = (function(fn) {
  366. return function(msg) { return fn(msg); };
  367. })(console.error);
  368. console.warn = (function(fn) {
  369. return function(msg) { return fn(msg); };
  370. })(console.warn);
  371. }
  372. })();
  373. // Check onclick compatibility in Opera
  374. // Support: Opera<15
  375. (function checkOnClickCompatibility() {
  376. // workaround for reported Opera bug DSK-354448:
  377. // onclick fires on disabled buttons with opaque content
  378. function ignoreIfTargetDisabled(event) {
  379. if (isDisabled(event.target)) {
  380. event.stopPropagation();
  381. }
  382. }
  383. function isDisabled(node) {
  384. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  385. }
  386. if (navigator.userAgent.indexOf('Opera') !== -1) {
  387. // use browser detection since we cannot feature-check this bug
  388. document.addEventListener('click', ignoreIfTargetDisabled, true);
  389. }
  390. })();
  391. // Checks if possible to use URL.createObjectURL()
  392. // Support: IE
  393. (function checkOnBlobSupport() {
  394. // sometimes IE loosing the data created with createObjectURL(), see #3977
  395. if (navigator.userAgent.indexOf('Trident') >= 0) {
  396. PDFJS.disableCreateObjectURL = true;
  397. }
  398. })();
  399. // Checks if navigator.language is supported
  400. (function checkNavigatorLanguage() {
  401. if ('language' in navigator &&
  402. /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {
  403. return;
  404. }
  405. function formatLocale(locale) {
  406. var split = locale.split(/[-_]/);
  407. split[0] = split[0].toLowerCase();
  408. if (split.length > 1) {
  409. split[1] = split[1].toUpperCase();
  410. }
  411. return split.join('-');
  412. }
  413. var language = navigator.language || navigator.userLanguage || 'en-US';
  414. PDFJS.locale = formatLocale(language);
  415. })();
  416. (function checkRangeRequests() {
  417. // Safari has issues with cached range requests see:
  418. // https://github.com/mozilla/pdf.js/issues/3260
  419. // Last tested with version 6.0.4.
  420. // Support: Safari 6.0+
  421. var isSafari = Object.prototype.toString.call(
  422. window.HTMLElement).indexOf('Constructor') > 0;
  423. // Older versions of Android (pre 3.0) has issues with range requests, see:
  424. // https://github.com/mozilla/pdf.js/issues/3381.
  425. // Make sure that we only match webkit-based Android browsers,
  426. // since Firefox/Fennec works as expected.
  427. // Support: Android<3.0
  428. var regex = /Android\s[0-2][^\d]/;
  429. var isOldAndroid = regex.test(navigator.userAgent);
  430. if (isSafari || isOldAndroid) {
  431. PDFJS.disableRange = 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. contextPrototype._createImageData = contextPrototype.createImageData;
  477. contextPrototype.createImageData = function(w, h) {
  478. var imageData = this._createImageData(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. }
  487. }
  488. })();
  489. // Support: IE<10, Android<4.0, iOS
  490. (function checkRequestAnimationFrame() {
  491. function fakeRequestAnimationFrame(callback) {
  492. window.setTimeout(callback, 20);
  493. }
  494. var isIOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  495. if (isIOS) {
  496. // requestAnimationFrame on iOS is broken, replacing with fake one.
  497. window.requestAnimationFrame = fakeRequestAnimationFrame;
  498. return;
  499. }
  500. if ('requestAnimationFrame' in window) {
  501. return;
  502. }
  503. window.requestAnimationFrame =
  504. window.mozRequestAnimationFrame ||
  505. window.webkitRequestAnimationFrame ||
  506. fakeRequestAnimationFrame;
  507. })();
  508. (function checkCanvasSizeLimitation() {
  509. var isIOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  510. var isAndroid = /Android/g.test(navigator.userAgent);
  511. if (isIOS || isAndroid) {
  512. // 5MP
  513. PDFJS.maxCanvasPixels = 5242880;
  514. }
  515. })();