Created
May 29, 2026 12:02
-
-
Save tomayac/2793a9c1f902c8248f29bade930342f2 to your computer and use it in GitHub Desktop.
Cross-origin worker script for COS extension testing (https://github.com/web-ai-community/cross-origin-storage-extension)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Copyright 2026 Google LLC. | |
| // SPDX-License-Identifier: Apache-2.0 | |
| // | |
| // Cross-origin worker script for the Cross-Origin Storage extension test page. | |
| // Hosted as a GitHub Gist so it is served from gist.githubusercontent.com, | |
| // which is cross-origin relative to the GitHub Pages deployment. The script | |
| // works as both a classic and a module worker (no top-level imports). | |
| // | |
| // Raw CORS headers from gist.githubusercontent.com include | |
| // Access-Control-Allow-Origin: *, so the browser will allow cross-origin | |
| // Worker construction without additional server configuration. | |
| async function sha256Hex(text) { | |
| const buf = await crypto.subtle.digest( | |
| 'SHA-256', | |
| new TextEncoder().encode(text), | |
| ); | |
| return Array.from(new Uint8Array(buf)) | |
| .map((b) => b.toString(16).padStart(2, '0')) | |
| .join(''); | |
| } | |
| function hashObj(value) { | |
| return { algorithm: 'SHA-256', value }; | |
| } | |
| self.onmessage = async ({ data }) => { | |
| if (data.type !== 'run') return; | |
| if (!self.navigator?.crossOriginStorage) { | |
| self.postMessage({ | |
| type: 'result', | |
| pass: false, | |
| detail: 'navigator.crossOriginStorage is undefined', | |
| }); | |
| return; | |
| } | |
| try { | |
| const content = `cos-variant-${data.label}`; | |
| const blob = new Blob([content], { type: 'text/plain' }); | |
| const hash = hashObj(await sha256Hex(content)); | |
| const [wh] = await navigator.crossOriginStorage.requestFileHandles( | |
| [hash], | |
| { create: true }, | |
| ); | |
| const writable = await wh.createWritable(); | |
| await writable.write(blob); | |
| await writable.close(); | |
| const [rh] = await navigator.crossOriginStorage.requestFileHandles([hash]); | |
| const text = await (await rh.getFile()).text(); | |
| const pass = text === content; | |
| self.postMessage({ | |
| type: 'result', | |
| pass, | |
| detail: pass | |
| ? `Stored and read back correctly: "${text}"` | |
| : `Expected "${content}", got "${text}"`, | |
| }); | |
| } catch (err) { | |
| self.postMessage({ | |
| type: 'result', | |
| pass: false, | |
| detail: `${err.name}: ${err.message}`, | |
| }); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment