From 3fa1499dd34a1f14299c1bde099f7dd594d865c8 Mon Sep 17 00:00:00 2001 From: Jeffrey Posnick Date: Mon, 26 Jun 2017 12:30:43 -0400 Subject: [PATCH] Determines whether PUBLIC_URL is same-origin before registering SW. (#2432) --- .../react-scripts/template/src/registerServiceWorker.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/react-scripts/template/src/registerServiceWorker.ts b/packages/react-scripts/template/src/registerServiceWorker.ts index 69e361673..318f94009 100644 --- a/packages/react-scripts/template/src/registerServiceWorker.ts +++ b/packages/react-scripts/template/src/registerServiceWorker.ts @@ -10,6 +10,15 @@ export default function register() { 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); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 + return; + } + window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; navigator.serviceWorker