Skip to content

Commit

Permalink
Update addAll() to reflect new behavior
Browse files Browse the repository at this point in the history
Make addAll() fail on responses other than OK in Firefox < 46 and Chrome < 50.
Also, if addAll() had to be fixed even though native exists--polyfill add()
method too. More details at w3c/ServiceWorker#823
  • Loading branch information
NekR committed Apr 4, 2016
1 parent 9043d94 commit 279470a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
35 changes: 33 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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() {
Expand Down Expand Up @@ -62,11 +81,23 @@ if (!Cache.prototype.addAll) {
// (don't think this is possible to polyfill due to opaque responses)
return Promise.all(
responses.map(function(response, i) {
if (!response.ok) {
throw new NetworkError('Incorrect response status');
}

return cache.put(requests[i], response);
})
);
}).then(function() {
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]);
};
}
}());
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down

0 comments on commit 279470a

Please sign in to comment.