compatibility.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. (function checkTypedArrayCompatibility() {
  26. if (typeof Uint8Array !== 'undefined') {
  27. // some mobile versions do not support subarray (e.g. safari 5 / iOS)
  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. // some mobile version might not support Float64Array
  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. (function normalizeURLObject() {
  89. if (!window.URL) {
  90. window.URL = window.webkitURL;
  91. }
  92. })();
  93. // Object.create() ?
  94. (function checkObjectCreateCompatibility() {
  95. if (typeof Object.create !== 'undefined') {
  96. return;
  97. }
  98. Object.create = function objectCreate(proto) {
  99. function Constructor() {}
  100. Constructor.prototype = proto;
  101. return new Constructor();
  102. };
  103. })();
  104. // Object.defineProperty() ?
  105. (function checkObjectDefinePropertyCompatibility() {
  106. if (typeof Object.defineProperty !== 'undefined') {
  107. var definePropertyPossible = true;
  108. try {
  109. // some browsers (e.g. safari) cannot use defineProperty() on DOM objects
  110. // and thus the native version is not sufficient
  111. Object.defineProperty(new Image(), 'id', { value: 'test' });
  112. // ... another test for android gb browser for non-DOM objects
  113. var Test = function Test() {};
  114. Test.prototype = { get id() { } };
  115. Object.defineProperty(new Test(), 'id',
  116. { value: '', configurable: true, enumerable: true, writable: false });
  117. } catch (e) {
  118. definePropertyPossible = false;
  119. }
  120. if (definePropertyPossible) {
  121. return;
  122. }
  123. }
  124. Object.defineProperty = function objectDefineProperty(obj, name, def) {
  125. delete obj[name];
  126. if ('get' in def) {
  127. obj.__defineGetter__(name, def['get']);
  128. }
  129. if ('set' in def) {
  130. obj.__defineSetter__(name, def['set']);
  131. }
  132. if ('value' in def) {
  133. obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
  134. this.__defineGetter__(name, function objectDefinePropertyGetter() {
  135. return value;
  136. });
  137. return value;
  138. });
  139. obj[name] = def.value;
  140. }
  141. };
  142. })();
  143. // Object.keys() ?
  144. (function checkObjectKeysCompatibility() {
  145. if (typeof Object.keys !== 'undefined') {
  146. return;
  147. }
  148. Object.keys = function objectKeys(obj) {
  149. var result = [];
  150. for (var i in obj) {
  151. if (obj.hasOwnProperty(i)) {
  152. result.push(i);
  153. }
  154. }
  155. return result;
  156. };
  157. })();
  158. // No readAsArrayBuffer ?
  159. (function checkFileReaderReadAsArrayBuffer() {
  160. if (typeof FileReader === 'undefined') {
  161. return; // FileReader is not implemented
  162. }
  163. var frPrototype = FileReader.prototype;
  164. // Older versions of Firefox might not have readAsArrayBuffer
  165. if ('readAsArrayBuffer' in frPrototype) {
  166. return; // readAsArrayBuffer is implemented
  167. }
  168. Object.defineProperty(frPrototype, 'readAsArrayBuffer', {
  169. value: function fileReaderReadAsArrayBuffer(blob) {
  170. var fileReader = new FileReader();
  171. var originalReader = this;
  172. fileReader.onload = function fileReaderOnload(evt) {
  173. var data = evt.target.result;
  174. var buffer = new ArrayBuffer(data.length);
  175. var uint8Array = new Uint8Array(buffer);
  176. for (var i = 0, ii = data.length; i < ii; i++) {
  177. uint8Array[i] = data.charCodeAt(i);
  178. }
  179. Object.defineProperty(originalReader, 'result', {
  180. value: buffer,
  181. enumerable: true,
  182. writable: false,
  183. configurable: true
  184. });
  185. var event = document.createEvent('HTMLEvents');
  186. event.initEvent('load', false, false);
  187. originalReader.dispatchEvent(event);
  188. };
  189. fileReader.readAsBinaryString(blob);
  190. }
  191. });
  192. })();
  193. // No XMLHttpRequest.response ?
  194. (function checkXMLHttpRequestResponseCompatibility() {
  195. var xhrPrototype = XMLHttpRequest.prototype;
  196. if (!('overrideMimeType' in xhrPrototype)) {
  197. // IE10 might have response, but not overrideMimeType
  198. Object.defineProperty(xhrPrototype, 'overrideMimeType', {
  199. value: function xmlHttpRequestOverrideMimeType(mimeType) {}
  200. });
  201. }
  202. if ('response' in xhrPrototype ||
  203. 'mozResponseArrayBuffer' in xhrPrototype ||
  204. 'mozResponse' in xhrPrototype ||
  205. 'responseArrayBuffer' in xhrPrototype) {
  206. return;
  207. }
  208. // IE9 ?
  209. if (typeof VBArray !== 'undefined') {
  210. Object.defineProperty(xhrPrototype, 'response', {
  211. get: function xmlHttpRequestResponseGet() {
  212. return new Uint8Array(new VBArray(this.responseBody).toArray());
  213. }
  214. });
  215. return;
  216. }
  217. // other browsers
  218. function responseTypeSetter() {
  219. // will be only called to set "arraybuffer"
  220. this.overrideMimeType('text/plain; charset=x-user-defined');
  221. }
  222. if (typeof xhrPrototype.overrideMimeType === 'function') {
  223. Object.defineProperty(xhrPrototype, 'responseType',
  224. { set: responseTypeSetter });
  225. }
  226. function responseGetter() {
  227. var text = this.responseText;
  228. var i, n = text.length;
  229. var result = new Uint8Array(n);
  230. for (i = 0; i < n; ++i) {
  231. result[i] = text.charCodeAt(i) & 0xFF;
  232. }
  233. return result;
  234. }
  235. Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
  236. })();
  237. // window.btoa (base64 encode function) ?
  238. (function checkWindowBtoaCompatibility() {
  239. if ('btoa' in window) {
  240. return;
  241. }
  242. var digits =
  243. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  244. window.btoa = function windowBtoa(chars) {
  245. var buffer = '';
  246. var i, n;
  247. for (i = 0, n = chars.length; i < n; i += 3) {
  248. var b1 = chars.charCodeAt(i) & 0xFF;
  249. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  250. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  251. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  252. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  253. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  254. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  255. digits.charAt(d3) + digits.charAt(d4));
  256. }
  257. return buffer;
  258. };
  259. })();
  260. // window.atob (base64 encode function) ?
  261. (function checkWindowAtobCompatibility() {
  262. if ('atob' in window) {
  263. return;
  264. }
  265. // https://github.com/davidchambers/Base64.js
  266. var digits =
  267. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  268. window.atob = function (input) {
  269. input = input.replace(/=+$/, '');
  270. if (input.length % 4 == 1) {
  271. throw new Error('bad atob input');
  272. }
  273. for (
  274. // initialize result and counters
  275. var bc = 0, bs, buffer, idx = 0, output = '';
  276. // get next character
  277. buffer = input.charAt(idx++);
  278. // character found in table?
  279. // initialize bit storage and add its ascii value
  280. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  281. // and if not first of each 4 characters,
  282. // convert the first 8 bits to one ascii character
  283. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  284. ) {
  285. // try to find character in table (0-63, not found => -1)
  286. buffer = digits.indexOf(buffer);
  287. }
  288. return output;
  289. };
  290. })();
  291. // Function.prototype.bind ?
  292. (function checkFunctionPrototypeBindCompatibility() {
  293. if (typeof Function.prototype.bind !== 'undefined') {
  294. return;
  295. }
  296. Function.prototype.bind = function functionPrototypeBind(obj) {
  297. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  298. var bound = function functionPrototypeBindBound() {
  299. var args = headArgs.concat(Array.prototype.slice.call(arguments));
  300. return fn.apply(obj, args);
  301. };
  302. return bound;
  303. };
  304. })();
  305. // HTMLElement dataset property
  306. (function checkDatasetProperty() {
  307. var div = document.createElement('div');
  308. if ('dataset' in div) {
  309. return; // dataset property exists
  310. }
  311. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  312. get: function() {
  313. if (this._dataset) {
  314. return this._dataset;
  315. }
  316. var dataset = {};
  317. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  318. var attribute = this.attributes[j];
  319. if (attribute.name.substring(0, 5) != 'data-') {
  320. continue;
  321. }
  322. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  323. function(all, ch) {
  324. return ch.toUpperCase();
  325. });
  326. dataset[key] = attribute.value;
  327. }
  328. Object.defineProperty(this, '_dataset', {
  329. value: dataset,
  330. writable: false,
  331. enumerable: false
  332. });
  333. return dataset;
  334. },
  335. enumerable: true
  336. });
  337. })();
  338. // HTMLElement classList property
  339. (function checkClassListProperty() {
  340. var div = document.createElement('div');
  341. if ('classList' in div) {
  342. return; // classList property exists
  343. }
  344. function changeList(element, itemName, add, remove) {
  345. var s = element.className || '';
  346. var list = s.split(/\s+/g);
  347. if (list[0] === '') {
  348. list.shift();
  349. }
  350. var index = list.indexOf(itemName);
  351. if (index < 0 && add) {
  352. list.push(itemName);
  353. }
  354. if (index >= 0 && remove) {
  355. list.splice(index, 1);
  356. }
  357. element.className = list.join(' ');
  358. return (index >= 0);
  359. }
  360. var classListPrototype = {
  361. add: function(name) {
  362. changeList(this.element, name, true, false);
  363. },
  364. contains: function(name) {
  365. return changeList(this.element, name, false, false);
  366. },
  367. remove: function(name) {
  368. changeList(this.element, name, false, true);
  369. },
  370. toggle: function(name) {
  371. changeList(this.element, name, true, true);
  372. }
  373. };
  374. Object.defineProperty(HTMLElement.prototype, 'classList', {
  375. get: function() {
  376. if (this._classList) {
  377. return this._classList;
  378. }
  379. var classList = Object.create(classListPrototype, {
  380. element: {
  381. value: this,
  382. writable: false,
  383. enumerable: true
  384. }
  385. });
  386. Object.defineProperty(this, '_classList', {
  387. value: classList,
  388. writable: false,
  389. enumerable: false
  390. });
  391. return classList;
  392. },
  393. enumerable: true
  394. });
  395. })();
  396. // Check console compatibility
  397. (function checkConsoleCompatibility() {
  398. if (!('console' in window)) {
  399. window.console = {
  400. log: function() {},
  401. error: function() {},
  402. warn: function() {}
  403. };
  404. } else if (!('bind' in console.log)) {
  405. // native functions in IE9 might not have bind
  406. console.log = (function(fn) {
  407. return function(msg) { return fn(msg); };
  408. })(console.log);
  409. console.error = (function(fn) {
  410. return function(msg) { return fn(msg); };
  411. })(console.error);
  412. console.warn = (function(fn) {
  413. return function(msg) { return fn(msg); };
  414. })(console.warn);
  415. }
  416. })();
  417. // Check onclick compatibility in Opera
  418. (function checkOnClickCompatibility() {
  419. // workaround for reported Opera bug DSK-354448:
  420. // onclick fires on disabled buttons with opaque content
  421. function ignoreIfTargetDisabled(event) {
  422. if (isDisabled(event.target)) {
  423. event.stopPropagation();
  424. }
  425. }
  426. function isDisabled(node) {
  427. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  428. }
  429. if (navigator.userAgent.indexOf('Opera') != -1) {
  430. // use browser detection since we cannot feature-check this bug
  431. document.addEventListener('click', ignoreIfTargetDisabled, true);
  432. }
  433. })();
  434. // Checks if possible to use URL.createObjectURL()
  435. (function checkOnBlobSupport() {
  436. // sometimes IE loosing the data created with createObjectURL(), see #3977
  437. if (navigator.userAgent.indexOf('Trident') >= 0) {
  438. PDFJS.disableCreateObjectURL = true;
  439. }
  440. })();
  441. // Checks if navigator.language is supported
  442. (function checkNavigatorLanguage() {
  443. if ('language' in navigator &&
  444. /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {
  445. return;
  446. }
  447. function formatLocale(locale) {
  448. var split = locale.split(/[-_]/);
  449. split[0] = split[0].toLowerCase();
  450. if (split.length > 1) {
  451. split[1] = split[1].toUpperCase();
  452. }
  453. return split.join('-');
  454. }
  455. var language = navigator.language || navigator.userLanguage || 'en-US';
  456. PDFJS.locale = formatLocale(language);
  457. })();
  458. (function checkRangeRequests() {
  459. // Safari has issues with cached range requests see:
  460. // https://github.com/mozilla/pdf.js/issues/3260
  461. // Last tested with version 6.0.4.
  462. var isSafari = Object.prototype.toString.call(
  463. window.HTMLElement).indexOf('Constructor') > 0;
  464. // Older versions of Android (pre 3.0) has issues with range requests, see:
  465. // https://github.com/mozilla/pdf.js/issues/3381.
  466. // Make sure that we only match webkit-based Android browsers,
  467. // since Firefox/Fennec works as expected.
  468. var regex = /Android\s[0-2][^\d]/;
  469. var isOldAndroid = regex.test(navigator.userAgent);
  470. if (isSafari || isOldAndroid) {
  471. PDFJS.disableRange = true;
  472. }
  473. })();
  474. // Check if the browser supports manipulation of the history.
  475. (function checkHistoryManipulation() {
  476. if (!window.history.pushState) {
  477. PDFJS.disableHistory = true;
  478. }
  479. })();
  480. (function checkSetPresenceInImageData() {
  481. if (window.CanvasPixelArray) {
  482. if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
  483. window.CanvasPixelArray.prototype.set = function(arr) {
  484. for (var i = 0, ii = this.length; i < ii; i++) {
  485. this[i] = arr[i];
  486. }
  487. };
  488. }
  489. }
  490. })();
  491. (function checkStorages() {
  492. // Feature test as per http://diveintohtml5.info/storage.html
  493. // The additional localStorage call is to get around a FF quirk, see
  494. // bug #495747 in bugzilla
  495. try {
  496. if ('localStorage' in window && window['localStorage'] !== null) {
  497. return;
  498. }
  499. } catch (e) { }
  500. // When the generic viewer is used in Firefox the following code will fail
  501. // when the preference 'network.cookie.lifetimePolicy' is set to 1,
  502. // see Mozilla bug 365772.
  503. try {
  504. window.localStorage = {
  505. data: Object.create(null),
  506. getItem: function (key) {
  507. return this.data[key];
  508. },
  509. setItem: function (key, value) {
  510. this.data[key] = value;
  511. }
  512. };
  513. } catch (e) {
  514. console.log('Unable to create polyfill for localStorage');
  515. }
  516. })();
  517. (function checkRequestAnimationFrame() {
  518. if ('requestAnimationFrame' in window) {
  519. return;
  520. }
  521. window.requestAnimationFrame =
  522. window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
  523. (function fakeRequestAnimationFrame(callback) {
  524. window.setTimeout(callback, 20);
  525. });
  526. })();