Home > OS >  How to enable SharedArrayBuffer in Microsoft Edge Javascript
How to enable SharedArrayBuffer in Microsoft Edge Javascript

Time:12-23

So the other day, I asked this question about javascript webworkers: Javascript Webworker how to put json information into array buffer. One of the answers I received was to use a SharedArrayBuffer to share memory between the main javascript and the webworker. I know that for a time, this was usable on microsoft edge, but for a security concern was disabled a while back. My edge version is 96.0.1054.62. Is there any way to enable using shared array buffers, in the browser configuration or settings? Currently, when I try to use it, it says that SharedArrayBuffer is undefined.

CodePudding user response:

In order for Shared Array Buffer support to be enabled, your web page needs to be in a secure context. To do this, you need your server to give the following headers: Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. You can read more about it on MDN

Changing the header on the server is the recommended way, but if you do not have the ability to manage headers on the server at all, then you can modify them through Service Workers. This blogpost describes enabling SharedArrayBuffer via header modification in ServiceWorker. It works in the following order:

  1. When the page is loaded for the first time, a Service worker is registered
  2. The page is reloaded
  3. SharedArrayBuffer becomes available because ServiceWorker controls all CORS headers for all requests

Service Worker modifies all requests by adding CORS/COEP headers (The example is taken from the mentioned blogpost):

self.addEventListener("install", function() {
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener("fetch", function(event) {
  if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
    return;
  }

  event.respondWith(
    fetch(event.request)
    .then(function(response) {
      // It seems like we only need to set the headers for index.html
      // If you want to be on the safe side, comment this out
      // if (!response.url.includes("index.html")) return response;

      const newHeaders = new Headers(response.headers);
      newHeaders.set("Cross-Origin-Embedder-Policy", "require-corp");
      newHeaders.set("Cross-Origin-Opener-Policy", "same-origin");

      const moddedResponse = new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: newHeaders,
      });

      return moddedResponse;
    })
    .catch(function(e) {
      console.error(e);
    })
  );
});

  • Related