SharedArrayBuffer Support and Cross-Origin Isolation
Detect SharedArrayBuffer availability, understand cross-origin isolation requirements (COOP/COEP headers), and implement shared memory between threads.
Detailed Explanation
SharedArrayBuffer Detection
SharedArrayBuffer enables shared memory between the main thread and Web Workers, allowing true multi-threaded programming in JavaScript. After the Spectre vulnerability, browsers require cross-origin isolation headers for this feature.
Detection
const hasSharedArrayBuffer =
typeof SharedArrayBuffer !== 'undefined';
Cross-Origin Isolation Check
function checkIsolation() {
return {
sharedArrayBuffer: typeof SharedArrayBuffer !== 'undefined',
crossOriginIsolated: window.crossOriginIsolated === true,
atomics: typeof Atomics !== 'undefined',
};
}
Required HTTP Headers
For SharedArrayBuffer to be available, the server must send these headers:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Why These Headers Are Needed
After the Spectre side-channel attack discovery in 2018, browsers disabled SharedArrayBuffer because it could be exploited for high-resolution timing attacks. The COOP and COEP headers re-enable it by ensuring the page cannot load cross-origin resources that have not explicitly opted in, preventing the attack vector.
Using SharedArrayBuffer
// Main thread
const buffer = new SharedArrayBuffer(1024);
const view = new Int32Array(buffer);
worker.postMessage({ buffer });
// Worker thread
onmessage = (e) => {
const view = new Int32Array(e.data.buffer);
Atomics.add(view, 0, 1); // Thread-safe increment
Atomics.notify(view, 0); // Wake waiting threads
};
Impact on Other Features
Enabling COEP may break cross-origin images, iframes, and scripts that do not set Cross-Origin-Resource-Policy headers. Plan your migration carefully.
Use Case
Required for multi-threaded WebAssembly (e.g., running Emscripten-compiled C++ with pthreads), parallel data processing in Web Workers, real-time audio/video processing, and high-performance scientific computing in the browser.