compatibility.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. return;
  40. }
  41. function subarray(start, end) {
  42. return new TypedArray(this.slice(start, end));
  43. }
  44. function setArrayOffset(array, offset) {
  45. if (arguments.length < 2)
  46. offset = 0;
  47. for (var i = 0, n = array.length; i < n; ++i, ++offset)
  48. this[offset] = array[i] & 0xFF;
  49. }
  50. function TypedArray(arg1) {
  51. var result;
  52. if (typeof arg1 === 'number') {
  53. result = [];
  54. for (var i = 0; i < arg1; ++i)
  55. result[i] = 0;
  56. } else if ('slice' in arg1) {
  57. result = arg1.slice(0);
  58. } else {
  59. result = [];
  60. for (var i = 0, n = arg1.length; i < n; ++i) {
  61. result[i] = arg1[i];
  62. }
  63. }
  64. result.subarray = subarray;
  65. result.buffer = result;
  66. result.byteLength = result.length;
  67. result.set = setArrayOffset;
  68. if (typeof arg1 === 'object' && arg1.buffer)
  69. result.buffer = arg1.buffer;
  70. return result;
  71. }
  72. window.Uint8Array = TypedArray;
  73. // we don't need support for set, byteLength for 32-bit array
  74. // so we can use the TypedArray as well
  75. window.Uint32Array = TypedArray;
  76. window.Int32Array = TypedArray;
  77. window.Uint16Array = TypedArray;
  78. window.Float32Array = TypedArray;
  79. window.Float64Array = TypedArray;
  80. })();
  81. // URL = URL || webkitURL
  82. (function normalizeURLObject() {
  83. if (!window.URL) {
  84. window.URL = window.webkitURL;
  85. }
  86. })();
  87. // Object.create() ?
  88. (function checkObjectCreateCompatibility() {
  89. if (typeof Object.create !== 'undefined')
  90. return;
  91. Object.create = function objectCreate(proto) {
  92. function Constructor() {}
  93. Constructor.prototype = proto;
  94. return new Constructor();
  95. };
  96. })();
  97. // Object.defineProperty() ?
  98. (function checkObjectDefinePropertyCompatibility() {
  99. if (typeof Object.defineProperty !== 'undefined') {
  100. var definePropertyPossible = true;
  101. try {
  102. // some browsers (e.g. safari) cannot use defineProperty() on DOM objects
  103. // and thus the native version is not sufficient
  104. Object.defineProperty(new Image(), 'id', { value: 'test' });
  105. // ... another test for android gb browser for non-DOM objects
  106. var Test = function Test() {};
  107. Test.prototype = { get id() { } };
  108. Object.defineProperty(new Test(), 'id',
  109. { value: '', configurable: true, enumerable: true, writable: false });
  110. } catch (e) {
  111. definePropertyPossible = false;
  112. }
  113. if (definePropertyPossible) return;
  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. if ('set' in def)
  120. obj.__defineSetter__(name, def['set']);
  121. if ('value' in def) {
  122. obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
  123. this.__defineGetter__(name, function objectDefinePropertyGetter() {
  124. return value;
  125. });
  126. return value;
  127. });
  128. obj[name] = def.value;
  129. }
  130. };
  131. })();
  132. // Object.keys() ?
  133. (function checkObjectKeysCompatibility() {
  134. if (typeof Object.keys !== 'undefined')
  135. return;
  136. Object.keys = function objectKeys(obj) {
  137. var result = [];
  138. for (var i in obj) {
  139. if (obj.hasOwnProperty(i))
  140. result.push(i);
  141. }
  142. return result;
  143. };
  144. })();
  145. // No readAsArrayBuffer ?
  146. (function checkFileReaderReadAsArrayBuffer() {
  147. if (typeof FileReader === 'undefined')
  148. return; // FileReader is not implemented
  149. var frPrototype = FileReader.prototype;
  150. // Older versions of Firefox might not have readAsArrayBuffer
  151. if ('readAsArrayBuffer' in frPrototype)
  152. return; // readAsArrayBuffer is implemented
  153. Object.defineProperty(frPrototype, 'readAsArrayBuffer', {
  154. value: function fileReaderReadAsArrayBuffer(blob) {
  155. var fileReader = new FileReader();
  156. var originalReader = this;
  157. fileReader.onload = function fileReaderOnload(evt) {
  158. var data = evt.target.result;
  159. var buffer = new ArrayBuffer(data.length);
  160. var uint8Array = new Uint8Array(buffer);
  161. for (var i = 0, ii = data.length; i < ii; i++)
  162. uint8Array[i] = data.charCodeAt(i);
  163. Object.defineProperty(originalReader, 'result', {
  164. value: buffer,
  165. enumerable: true,
  166. writable: false,
  167. configurable: true
  168. });
  169. var event = document.createEvent('HTMLEvents');
  170. event.initEvent('load', false, false);
  171. originalReader.dispatchEvent(event);
  172. };
  173. fileReader.readAsBinaryString(blob);
  174. }
  175. });
  176. })();
  177. // No XMLHttpRequest.response ?
  178. (function checkXMLHttpRequestResponseCompatibility() {
  179. var xhrPrototype = XMLHttpRequest.prototype;
  180. if (!('overrideMimeType' in xhrPrototype)) {
  181. // IE10 might have response, but not overrideMimeType
  182. Object.defineProperty(xhrPrototype, 'overrideMimeType', {
  183. value: function xmlHttpRequestOverrideMimeType(mimeType) {}
  184. });
  185. }
  186. if ('response' in xhrPrototype ||
  187. 'mozResponseArrayBuffer' in xhrPrototype ||
  188. 'mozResponse' in xhrPrototype ||
  189. 'responseArrayBuffer' in xhrPrototype)
  190. return;
  191. // IE9 ?
  192. if (typeof VBArray !== 'undefined') {
  193. Object.defineProperty(xhrPrototype, 'response', {
  194. get: function xmlHttpRequestResponseGet() {
  195. return new Uint8Array(new VBArray(this.responseBody).toArray());
  196. }
  197. });
  198. return;
  199. }
  200. // other browsers
  201. function responseTypeSetter() {
  202. // will be only called to set "arraybuffer"
  203. this.overrideMimeType('text/plain; charset=x-user-defined');
  204. }
  205. if (typeof xhrPrototype.overrideMimeType === 'function') {
  206. Object.defineProperty(xhrPrototype, 'responseType',
  207. { set: responseTypeSetter });
  208. }
  209. function responseGetter() {
  210. var text = this.responseText;
  211. var i, n = text.length;
  212. var result = new Uint8Array(n);
  213. for (i = 0; i < n; ++i)
  214. result[i] = text.charCodeAt(i) & 0xFF;
  215. return result;
  216. }
  217. Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
  218. })();
  219. // window.btoa (base64 encode function) ?
  220. (function checkWindowBtoaCompatibility() {
  221. if ('btoa' in window)
  222. return;
  223. var digits =
  224. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  225. window.btoa = function windowBtoa(chars) {
  226. var buffer = '';
  227. var i, n;
  228. for (i = 0, n = chars.length; i < n; i += 3) {
  229. var b1 = chars.charCodeAt(i) & 0xFF;
  230. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  231. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  232. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  233. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  234. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  235. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  236. digits.charAt(d3) + digits.charAt(d4));
  237. }
  238. return buffer;
  239. };
  240. })();
  241. // window.atob (base64 encode function) ?
  242. (function checkWindowAtobCompatibility() {
  243. if ('atob' in window)
  244. return;
  245. // https://github.com/davidchambers/Base64.js
  246. var digits =
  247. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  248. window.atob = function (input) {
  249. input = input.replace(/=+$/, '');
  250. if (input.length % 4 == 1) throw new Error('bad atob input');
  251. for (
  252. // initialize result and counters
  253. var bc = 0, bs, buffer, idx = 0, output = '';
  254. // get next character
  255. buffer = input.charAt(idx++);
  256. // character found in table?
  257. // initialize bit storage and add its ascii value
  258. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  259. // and if not first of each 4 characters,
  260. // convert the first 8 bits to one ascii character
  261. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  262. ) {
  263. // try to find character in table (0-63, not found => -1)
  264. buffer = digits.indexOf(buffer);
  265. }
  266. return output;
  267. };
  268. })();
  269. // Function.prototype.bind ?
  270. (function checkFunctionPrototypeBindCompatibility() {
  271. if (typeof Function.prototype.bind !== 'undefined')
  272. return;
  273. Function.prototype.bind = function functionPrototypeBind(obj) {
  274. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  275. var bound = function functionPrototypeBindBound() {
  276. var args = Array.prototype.concat.apply(headArgs, arguments);
  277. return fn.apply(obj, args);
  278. };
  279. return bound;
  280. };
  281. })();
  282. // HTMLElement dataset property
  283. (function checkDatasetProperty() {
  284. var div = document.createElement('div');
  285. if ('dataset' in div)
  286. return; // dataset property exists
  287. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  288. get: function() {
  289. if (this._dataset)
  290. return this._dataset;
  291. var dataset = {};
  292. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  293. var attribute = this.attributes[j];
  294. if (attribute.name.substring(0, 5) != 'data-')
  295. continue;
  296. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  297. function(all, ch) { return ch.toUpperCase(); });
  298. dataset[key] = attribute.value;
  299. }
  300. Object.defineProperty(this, '_dataset', {
  301. value: dataset,
  302. writable: false,
  303. enumerable: false
  304. });
  305. return dataset;
  306. },
  307. enumerable: true
  308. });
  309. })();
  310. // HTMLElement classList property
  311. (function checkClassListProperty() {
  312. var div = document.createElement('div');
  313. if ('classList' in div)
  314. return; // classList property exists
  315. function changeList(element, itemName, add, remove) {
  316. var s = element.className || '';
  317. var list = s.split(/\s+/g);
  318. if (list[0] === '') list.shift();
  319. var index = list.indexOf(itemName);
  320. if (index < 0 && add)
  321. list.push(itemName);
  322. if (index >= 0 && remove)
  323. list.splice(index, 1);
  324. element.className = list.join(' ');
  325. return (index >= 0);
  326. }
  327. var classListPrototype = {
  328. add: function(name) {
  329. changeList(this.element, name, true, false);
  330. },
  331. contains: function(name) {
  332. return changeList(this.element, name, false, false);
  333. },
  334. remove: function(name) {
  335. changeList(this.element, name, false, true);
  336. },
  337. toggle: function(name) {
  338. changeList(this.element, name, true, true);
  339. }
  340. };
  341. Object.defineProperty(HTMLElement.prototype, 'classList', {
  342. get: function() {
  343. if (this._classList)
  344. return this._classList;
  345. var classList = Object.create(classListPrototype, {
  346. element: {
  347. value: this,
  348. writable: false,
  349. enumerable: true
  350. }
  351. });
  352. Object.defineProperty(this, '_classList', {
  353. value: classList,
  354. writable: false,
  355. enumerable: false
  356. });
  357. return classList;
  358. },
  359. enumerable: true
  360. });
  361. })();
  362. // Check console compatibility
  363. (function checkConsoleCompatibility() {
  364. if (!('console' in window)) {
  365. window.console = {
  366. log: function() {},
  367. error: function() {},
  368. warn: function() {}
  369. };
  370. } else if (!('bind' in console.log)) {
  371. // native functions in IE9 might not have bind
  372. console.log = (function(fn) {
  373. return function(msg) { return fn(msg); };
  374. })(console.log);
  375. console.error = (function(fn) {
  376. return function(msg) { return fn(msg); };
  377. })(console.error);
  378. console.warn = (function(fn) {
  379. return function(msg) { return fn(msg); };
  380. })(console.warn);
  381. }
  382. })();
  383. // Check onclick compatibility in Opera
  384. (function checkOnClickCompatibility() {
  385. // workaround for reported Opera bug DSK-354448:
  386. // onclick fires on disabled buttons with opaque content
  387. function ignoreIfTargetDisabled(event) {
  388. if (isDisabled(event.target)) {
  389. event.stopPropagation();
  390. }
  391. }
  392. function isDisabled(node) {
  393. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  394. }
  395. if (navigator.userAgent.indexOf('Opera') != -1) {
  396. // use browser detection since we cannot feature-check this bug
  397. document.addEventListener('click', ignoreIfTargetDisabled, true);
  398. }
  399. })();
  400. // Checks if possible to use URL.createObjectURL()
  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. Object.defineProperty(navigator, 'language', {
  412. get: function navigatorLanguage() {
  413. var language = navigator.userLanguage || 'en-US';
  414. return language.substring(0, 2).toLowerCase() +
  415. language.substring(2).toUpperCase();
  416. },
  417. enumerable: true
  418. });
  419. })();
  420. (function checkRangeRequests() {
  421. // Safari has issues with cached range requests see:
  422. // https://github.com/mozilla/pdf.js/issues/3260
  423. // Last tested with version 6.0.4.
  424. var isSafari = Object.prototype.toString.call(
  425. window.HTMLElement).indexOf('Constructor') > 0;
  426. // Older versions of Android (pre 3.0) has issues with range requests, see:
  427. // https://github.com/mozilla/pdf.js/issues/3381.
  428. // Make sure that we only match webkit-based Android browsers,
  429. // since Firefox/Fennec works as expected.
  430. var regex = /Android\s[0-2][^\d]/;
  431. var isOldAndroid = regex.test(navigator.userAgent);
  432. if (isSafari || isOldAndroid) {
  433. PDFJS.disableRange = true;
  434. }
  435. })();
  436. // Check if the browser supports manipulation of the history.
  437. (function checkHistoryManipulation() {
  438. if (!window.history.pushState) {
  439. PDFJS.disableHistory = true;
  440. }
  441. })();