Skip to content

Commit

Permalink
Web: Added DILIGENT_EMSCRIPTEN_INCLUDE_COI_SERVICE_WORKER option (close
Browse files Browse the repository at this point in the history
  • Loading branch information
MikhailGorobets committed Aug 28, 2024
1 parent 7dbebca commit 298fadd
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 3 deletions.
5 changes: 3 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ else()
set(DILIGENT_INSTALL_SAMPLES OFF)
endif()

option(DILIGENT_BUILD_SAMPLE_BASE_ONLY "Build only SampleBase project" OFF)
option(DILIGENT_EMSCRIPTEN_STRIP_DEBUG_INFO "Strip debug information from Emscripten build" OFF)
option(DILIGENT_BUILD_SAMPLE_BASE_ONLY "Build only SampleBase project" OFF)
option(DILIGENT_EMSCRIPTEN_STRIP_DEBUG_INFO "Strip debug information from Emscripten build" OFF)
option(DILIGENT_EMSCRIPTEN_INCLUDE_COI_SERVICE_WORKER "Include cross-origin isolation service worker in each emscripten build" OFF)

function(add_sample_app APP_NAME IDE_FOLDER SOURCE INCLUDE SHADERS ASSETS)

Expand Down
6 changes: 6 additions & 0 deletions SampleBase/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ elseif(PLATFORM_EMSCRIPTEN)
set(DILIGENT_DISABLE_WEBGL "disabled")
endif()

if (DILIGENT_EMSCRIPTEN_INCLUDE_COI_SERVICE_WORKER)
set(DILIGENT_COI_SERVICE_WORKER_SCRIPT "<script src=\"coi-serviceworker.js\"></script>")
file(COPY ${SAMPLE_BASE_SOURCE_DIR}/src/Emscripten/resources/coi-serviceworker.js DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
else()
set(DILIGENT_COI_SERVICE_WORKER_SCRIPT "")
endif()

configure_file(
${SAMPLE_BASE_SOURCE_DIR}/src/Emscripten/resources/emscripten_template.html.in
Expand Down
146 changes: 146 additions & 0 deletions SampleBase/src/Emscripten/resources/coi-serviceworker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*! coi-serviceworker v0.1.7 - Guido Zuidhof and contributors, licensed under MIT */
let coepCredentialless = false;
if (typeof window === 'undefined') {
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));

self.addEventListener("message", (ev) => {
if (!ev.data) {
return;
} else if (ev.data.type === "deregister") {
self.registration
.unregister()
.then(() => {
return self.clients.matchAll();
})
.then(clients => {
clients.forEach((client) => client.navigate(client.url));
});
} else if (ev.data.type === "coepCredentialless") {
coepCredentialless = ev.data.value;
}
});

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

const request = (coepCredentialless && r.mode === "no-cors")
? new Request(r, {
credentials: "omit",
})
: r;
event.respondWith(
fetch(request)
.then((response) => {
if (response.status === 0) {
return response;
}

const newHeaders = new Headers(response.headers);
newHeaders.set("Cross-Origin-Embedder-Policy",
coepCredentialless ? "credentialless" : "require-corp"
);
if (!coepCredentialless) {
newHeaders.set("Cross-Origin-Resource-Policy", "cross-origin");
}
newHeaders.set("Cross-Origin-Opener-Policy", "same-origin");

return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
})
.catch((e) => console.error(e))
);
});

} else {
(() => {
const reloadedBySelf = window.sessionStorage.getItem("coiReloadedBySelf");
window.sessionStorage.removeItem("coiReloadedBySelf");
const coepDegrading = (reloadedBySelf == "coepdegrade");

// You can customize the behavior of this script through a global `coi` variable.
const coi = {
shouldRegister: () => !reloadedBySelf,
shouldDeregister: () => false,
coepCredentialless: () => true,
coepDegrade: () => true,
doReload: () => window.location.reload(),
quiet: false,
...window.coi
};

const n = navigator;
const controlling = n.serviceWorker && n.serviceWorker.controller;

// Record the failure if the page is served by serviceWorker.
if (controlling && !window.crossOriginIsolated) {
window.sessionStorage.setItem("coiCoepHasFailed", "true");
}
const coepHasFailed = window.sessionStorage.getItem("coiCoepHasFailed");

if (controlling) {
// Reload only on the first failure.
const reloadToDegrade = coi.coepDegrade() && !(
coepDegrading || window.crossOriginIsolated
);
n.serviceWorker.controller.postMessage({
type: "coepCredentialless",
value: (reloadToDegrade || coepHasFailed && coi.coepDegrade())
? false
: coi.coepCredentialless(),
});
if (reloadToDegrade) {
!coi.quiet && console.log("Reloading page to degrade COEP.");
window.sessionStorage.setItem("coiReloadedBySelf", "coepdegrade");
coi.doReload("coepdegrade");
}

if (coi.shouldDeregister()) {
n.serviceWorker.controller.postMessage({ type: "deregister" });
}
}

// If we're already coi: do nothing. Perhaps it's due to this script doing its job, or COOP/COEP are
// already set from the origin server. Also if the browser has no notion of crossOriginIsolated, just give up here.
if (window.crossOriginIsolated !== false || !coi.shouldRegister()) return;

if (!window.isSecureContext) {
!coi.quiet && console.log("COOP/COEP Service Worker not registered, a secure context is required.");
return;
}

// In some environments (e.g. Firefox private mode) this won't be available
if (!n.serviceWorker) {
!coi.quiet && console.error("COOP/COEP Service Worker not registered, perhaps due to private mode.");
return;
}

n.serviceWorker.register(window.document.currentScript.src).then(
(registration) => {
!coi.quiet && console.log("COOP/COEP Service Worker registered", registration.scope);

registration.addEventListener("updatefound", () => {
!coi.quiet && console.log("Reloading page to make use of updated COOP/COEP Service Worker.");
window.sessionStorage.setItem("coiReloadedBySelf", "updatefound");
coi.doReload();
});

// If the registration is active, but it's not controlling the page
if (registration.active && !n.serviceWorker.controller) {
!coi.quiet && console.log("Reloading page to make use of COOP/COEP Service Worker.");
window.sessionStorage.setItem("coiReloadedBySelf", "notcontrolling");
coi.doReload();
}
},
(err) => {
!coi.quiet && console.error("COOP/COEP Service Worker failed to register:", err);
}
);
})();
}
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@
The application may not run properly on this browser. For best results, we recommend using Chrome.
</div>
</div>


@DILIGENT_COI_SERVICE_WORKER_SCRIPT@
<script type='text/javascript'>
function detectBrowser() {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
Expand Down

0 comments on commit 298fadd

Please sign in to comment.