diff --git a/index.js b/index.js index 7b4e6bf..3b13c21 100644 --- a/index.js +++ b/index.js @@ -15,7 +15,25 @@ * */ -if (!Cache.prototype.addAll) { +(function() { + var nativeAddAll = Cache.prototype.addAll; + var userAgent = navigator.userAgent.match(/(Firefox|Chrome)\/(\d+\.)/); + + // Has nice behavior of `var` which everyone hates + if (userAgent) { + var agent = userAgent[1]; + var version = parseInt(userAgent[2]); + } + + if ( + nativeAddAll && (!userAgent || + (agent === 'Firefox' && version >= 46) || + (agent === 'Chrome' && version >= 50) + ) + ) { + return; + } + Cache.prototype.addAll = function addAll(requests) { var cache = this; @@ -25,6 +43,7 @@ if (!Cache.prototype.addAll) { this.code = 19; this.message = message; } + NetworkError.prototype = Object.create(Error.prototype); return Promise.resolve().then(function() { @@ -58,6 +77,14 @@ if (!Cache.prototype.addAll) { }) ); }).then(function(responses) { + // If some of the responses has not OK-eish status, + // then whole operation should reject + if (responses.some(function(response) { + return !response.ok; + })) { + throw new NetworkError('Incorrect response status'); + } + // TODO: check that requests don't overwrite one another // (don't think this is possible to polyfill due to opaque responses) return Promise.all( @@ -69,4 +96,12 @@ if (!Cache.prototype.addAll) { return undefined; }); }; -} + + // Has native addAll(), but it has to be fixed anyway. + // So add() has to be fixed too + if (nativeAddAll) { + Cache.prototype.add = function add(request) { + return this.addAll([request]); + }; + } +}()); \ No newline at end of file diff --git a/package.json b/package.json index 8e1a97f..e070246 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "serviceworker-cache-polyfill", - "version": "3.0.0", + "version": "4.0.0", "description": "Cache polyfill for the ServiceWorker", "main": "index.js", "scripts": {