diff --git a/demo/demo-sw.js b/demo/demo-sw.js index 90d430b..5f68fac 100644 --- a/demo/demo-sw.js +++ b/demo/demo-sw.js @@ -12,8 +12,34 @@ self.addEventListener('install', function(event) { self.addEventListener('activate', () => self.clients.claim()); // Intercept fetch requests for modules and compile the intercepted typescript. +// Whether a URL is one we're willing to intercept and compile. +// Not just https: a service worker also runs on http://localhost and +// http://127.0.0.1, because those are secure contexts. Testing the scheme alone +// makes the whole demo silently do nothing when served locally over http - no +// TypeScript is ever transpiled, so the page loads but none of its code runs. +const isCompilableUrl = (url) => { + try { + const u = new URL(url); + if (u.protocol === 'https:') { return true; } + return u.protocol === 'http:' + && (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'); + } catch { + return false; + } +}; + +// Local development should always recompile rather than serve a stale build. +const isLocalUrl = (url) => { + try { + const u = new URL(url); + return u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'; + } catch { + return false; + } +}; + self.addEventListener('fetch', (event) => { - if (!event.request.url.startsWith('https://')) { + if (!isCompilableUrl(event.request.url)) { return; } @@ -107,7 +133,7 @@ const transpileTypeScript = async (requestUrl) => { }; const transpiledResponse = new Response(transpiledCode, responseOptions); - if (!requestUrl.startsWith('https://localhost') && requestUrl.startsWith('https://')) { + if (!isLocalUrl(requestUrl)) { typescriptCache.put(requestUrl, transpiledResponse.clone()); } diff --git a/demo/index.html b/demo/index.html index b8861d5..34202a6 100644 --- a/demo/index.html +++ b/demo/index.html @@ -67,8 +67,11 @@ // ChromeOS works out of the box! - // WebUSB requires HTTPS, show an error if the page wasn't loaded securely. - if (location.protocol !== 'https:') { + // WebUSB requires a secure context, show an error if the page wasn't + // loaded in one. Note this is NOT the same as checking for https: + // http://localhost (and 127.0.0.1, and file:) are secure contexts too, + // which is what makes local development possible at all. + if (!window.isSecureContext) { document.getElementById('urlNotSecure').classList.remove('d-none'); } @@ -113,7 +116,10 @@ vendorId: 0x2730, // Citizen }, { - vendorId: 0x04B8 // Epson + vendorId: 0x04B8, // Epson + }, + { + vendorId: 0x0aa7, // Wincor Nixdorf (TH230, ESC/POS) } ] } @@ -457,8 +463,8 @@

Your browser doesn't support WebUSB

This demo uses WebUSB to function and your browser doesn't seem to have that available. Try using one that has WebUSB.