compatibility.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. return new Uint8Array(new VBArray(this.responseBody).toArray());
  157. }
  158. });
  159. return;
  160. }
  161. // other browsers
  162. function responseTypeSetter() {
  163. // will be only called to set "arraybuffer"
  164. this.overrideMimeType('text/plain; charset=x-user-defined');
  165. }
  166. if (typeof xhr.overrideMimeType === 'function') {
  167. Object.defineProperty(xhrPrototype, 'responseType',
  168. { set: responseTypeSetter });
  169. }
  170. function responseGetter() {
  171. var text = this.responseText;
  172. var i, n = text.length;
  173. var result = new Uint8Array(n);
  174. for (i = 0; i < n; ++i) {
  175. result[i] = text.charCodeAt(i) & 0xFF;
  176. }
  177. return result.buffer;
  178. }
  179. Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
  180. })();
  181. // window.btoa (base64 encode function) ?
  182. // Support: IE<10
  183. (function checkWindowBtoaCompatibility() {
  184. if ('btoa' in window) {
  185. return;
  186. }
  187. var digits =
  188. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  189. window.btoa = function windowBtoa(chars) {
  190. var buffer = '';
  191. var i, n;
  192. for (i = 0, n = chars.length; i < n; i += 3) {
  193. var b1 = chars.charCodeAt(i) & 0xFF;
  194. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  195. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  196. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  197. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  198. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  199. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  200. digits.charAt(d3) + digits.charAt(d4));
  201. }
  202. return buffer;
  203. };
  204. })();
  205. // window.atob (base64 encode function)?
  206. // Support: IE<10
  207. (function checkWindowAtobCompatibility() {
  208. if ('atob' in window) {
  209. return;
  210. }
  211. // https://github.com/davidchambers/Base64.js
  212. var digits =
  213. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  214. window.atob = function (input) {
  215. input = input.replace(/=+$/, '');
  216. if (input.length % 4 == 1) {
  217. throw new Error('bad atob input');
  218. }
  219. for (
  220. // initialize result and counters
  221. var bc = 0, bs, buffer, idx = 0, output = '';
  222. // get next character
  223. buffer = input.charAt(idx++);
  224. // character found in table?
  225. // initialize bit storage and add its ascii value
  226. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  227. // and if not first of each 4 characters,
  228. // convert the first 8 bits to one ascii character
  229. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  230. ) {
  231. // try to find character in table (0-63, not found => -1)
  232. buffer = digits.indexOf(buffer);
  233. }
  234. return output;
  235. };
  236. })();
  237. // Function.prototype.bind?
  238. // Support: Android<4.0, iOS<6.0
  239. (function checkFunctionPrototypeBindCompatibility() {
  240. if (typeof Function.prototype.bind !== 'undefined') {
  241. return;
  242. }
  243. Function.prototype.bind = function functionPrototypeBind(obj) {
  244. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  245. var bound = function functionPrototypeBindBound() {
  246. var args = headArgs.concat(Array.prototype.slice.call(arguments));
  247. return fn.apply(obj, args);
  248. };
  249. return bound;
  250. };
  251. })();
  252. // HTMLElement dataset property
  253. // Support: IE<11, Safari<5.1, Android<4.0
  254. (function checkDatasetProperty() {
  255. var div = document.createElement('div');
  256. if ('dataset' in div) {
  257. return; // dataset property exists
  258. }
  259. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  260. get: function() {
  261. if (this._dataset) {
  262. return this._dataset;
  263. }
  264. var dataset = {};
  265. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  266. var attribute = this.attributes[j];
  267. if (attribute.name.substring(0, 5) != 'data-') {
  268. continue;
  269. }
  270. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  271. function(all, ch) {
  272. return ch.toUpperCase();
  273. });
  274. dataset[key] = attribute.value;
  275. }
  276. Object.defineProperty(this, '_dataset', {
  277. value: dataset,
  278. writable: false,
  279. enumerable: false
  280. });
  281. return dataset;
  282. },
  283. enumerable: true
  284. });
  285. })();
  286. // HTMLElement classList property
  287. // Support: IE<10, Android<4.0, iOS<5.0
  288. (function checkClassListProperty() {
  289. var div = document.createElement('div');
  290. if ('classList' in div) {
  291. return; // classList property exists
  292. }
  293. function changeList(element, itemName, add, remove) {
  294. var s = element.className || '';
  295. var list = s.split(/\s+/g);
  296. if (list[0] === '') {
  297. list.shift();
  298. }
  299. var index = list.indexOf(itemName);
  300. if (index < 0 && add) {
  301. list.push(itemName);
  302. }
  303. if (index >= 0 && remove) {
  304. list.splice(index, 1);
  305. }
  306. element.className = list.join(' ');
  307. return (index >= 0);
  308. }
  309. var classListPrototype = {
  310. add: function(name) {
  311. changeList(this.element, name, true, false);
  312. },
  313. contains: function(name) {
  314. return changeList(this.element, name, false, false);
  315. },
  316. remove: function(name) {
  317. changeList(this.element, name, false, true);
  318. },
  319. toggle: function(name) {
  320. changeList(this.element, name, true, true);
  321. }
  322. };
  323. Object.defineProperty(HTMLElement.prototype, 'classList', {
  324. get: function() {
  325. if (this._classList) {
  326. return this._classList;
  327. }
  328. var classList = Object.create(classListPrototype, {
  329. element: {
  330. value: this,
  331. writable: false,
  332. enumerable: true
  333. }
  334. });
  335. Object.defineProperty(this, '_classList', {
  336. value: classList,
  337. writable: false,
  338. enumerable: false
  339. });
  340. return classList;
  341. },
  342. enumerable: true
  343. });
  344. })();
  345. // Check console compatibility
  346. // In older IE versions the console object is not available
  347. // unless console is open.
  348. // Support: IE<10
  349. (function checkConsoleCompatibility() {
  350. if (!('console' in window)) {
  351. window.console = {
  352. log: function() {},
  353. error: function() {},
  354. warn: function() {}
  355. };
  356. } else if (!('bind' in console.log)) {
  357. // native functions in IE9 might not have bind
  358. console.log = (function(fn) {
  359. return function(msg) { return fn(msg); };
  360. })(console.log);
  361. console.error = (function(fn) {
  362. return function(msg) { return fn(msg); };
  363. })(console.error);
  364. console.warn = (function(fn) {
  365. return function(msg) { return fn(msg); };
  366. })(console.warn);
  367. }
  368. })();
  369. // Check onclick compatibility in Opera
  370. // Support: Opera<15
  371. (function checkOnClickCompatibility() {
  372. // workaround for reported Opera bug DSK-354448:
  373. // onclick fires on disabled buttons with opaque content
  374. function ignoreIfTargetDisabled(event) {
  375. if (isDisabled(event.target)) {
  376. event.stopPropagation();
  377. }
  378. }
  379. function isDisabled(node) {
  380. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  381. }
  382. if (navigator.userAgent.indexOf('Opera') != -1) {
  383. // use browser detection since we cannot feature-check this bug
  384. document.addEventListener('click', ignoreIfTargetDisabled, true);
  385. }
  386. })();
  387. // Checks if possible to use URL.createObjectURL()
  388. // Support: IE
  389. (function checkOnBlobSupport() {
  390. // sometimes IE loosing the data created with createObjectURL(), see #3977
  391. if (navigator.userAgent.indexOf('Trident') >= 0) {
  392. PDFJS.disableCreateObjectURL = true;
  393. }
  394. })();
  395. // Checks if navigator.language is supported
  396. (function checkNavigatorLanguage() {
  397. if ('language' in navigator &&
  398. /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {
  399. return;
  400. }
  401. function formatLocale(locale) {
  402. var split = locale.split(/[-_]/);
  403. split[0] = split[0].toLowerCase();
  404. if (split.length > 1) {
  405. split[1] = split[1].toUpperCase();
  406. }
  407. return split.join('-');
  408. }
  409. var language = navigator.language || navigator.userLanguage || 'en-US';
  410. PDFJS.locale = formatLocale(language);
  411. })();
  412. (function checkRangeRequests() {
  413. // Safari has issues with cached range requests see:
  414. // https://github.com/mozilla/pdf.js/issues/3260
  415. // Last tested with version 6.0.4.
  416. // Support: Safari 6.0+
  417. var isSafari = Object.prototype.toString.call(
  418. window.HTMLElement).indexOf('Constructor') > 0;
  419. // Older versions of Android (pre 3.0) has issues with range requests, see:
  420. // https://github.com/mozilla/pdf.js/issues/3381.
  421. // Make sure that we only match webkit-based Android browsers,
  422. // since Firefox/Fennec works as expected.
  423. // Support: Android<3.0
  424. var regex = /Android\s[0-2][^\d]/;
  425. var isOldAndroid = regex.test(navigator.userAgent);
  426. if (isSafari || isOldAndroid) {
  427. PDFJS.disableRange = true;
  428. }
  429. })();
  430. // Check if the browser supports manipulation of the history.
  431. // Support: IE<10, Android<4.2
  432. (function checkHistoryManipulation() {
  433. // Android 2.x has so buggy pushState support that it was removed in
  434. // Android 3.0 and restored as late as in Android 4.2.
  435. // Support: Android 2.x
  436. if (!history.pushState || navigator.userAgent.indexOf('Android 2.') >= 0) {
  437. PDFJS.disableHistory = true;
  438. }
  439. })();
  440. // TODO CanvasPixelArray is deprecated; use Uint8ClampedArray
  441. // once it's supported.
  442. (function checkSetPresenceInImageData() {
  443. if (window.CanvasPixelArray) {
  444. if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
  445. window.CanvasPixelArray.prototype.set = function(arr) {
  446. for (var i = 0, ii = this.length; i < ii; i++) {
  447. this[i] = arr[i];
  448. }
  449. };
  450. }
  451. }
  452. })();
  453. // Support: IE<10, Android<4.0, iOS<5.0
  454. (function checkRequestAnimationFrame() {
  455. if ('requestAnimationFrame' in window) {
  456. return;
  457. }
  458. window.requestAnimationFrame =
  459. window.mozRequestAnimationFrame ||
  460. window.webkitRequestAnimationFrame ||
  461. (function fakeRequestAnimationFrame(callback) {
  462. window.setTimeout(callback, 20);
  463. });
  464. })();