Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide callbacks in registerServiceWorker (1.x) #3375

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions packages/react-scripts/template/src/registerServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const isLocalhost = Boolean(
)
);

export default function register() {
export default function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
Expand All @@ -34,7 +34,7 @@ export default function register() {

if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
checkValidServiceWorker(swUrl, config);

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
Expand All @@ -46,13 +46,13 @@ export default function register() {
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
registerValidSW(swUrl, config);
}
});
}
}

function registerValidSW(swUrl) {
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
Expand All @@ -66,11 +66,21 @@ function registerValidSW(swUrl) {
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');

// Execute callback
if (config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');

// Execute callback
if (config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
Expand All @@ -81,7 +91,7 @@ function registerValidSW(swUrl) {
});
}

function checkValidServiceWorker(swUrl) {
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
Expand All @@ -98,7 +108,7 @@ function checkValidServiceWorker(swUrl) {
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
registerValidSW(swUrl, config);
}
})
.catch(() => {
Expand Down