Add compatibility for Cloudflare Workers#784
Add compatibility for Cloudflare Workers#784Rohan487 wants to merge 3 commits intogram-js:masterfrom
Conversation
|
related #506 |
|
Hi, thank you for testing the library with Cloudflare Workers. It is also something that I am considering trying. What if you use the following approach? +export const isCloudflareWorker = typeof navigator !== "undefined" ? navigator.userAgent == "Cloudflare-Workers" : false
-export const isBrowser = !isDeno && typeof window !== "undefined"
+export const isBrowser = isCloudflareWorker || (!isDeno && typeof window !== "undefined")
export const isNode = !isBrowser;It should reduce the amount of changes needed in the library |
|
Hey! Thanks for the suggestion — it's a thoughtful optimization for reducing code changes. However, I’d like to clarify why treating isCloudflareWorker as part of the isBrowser check can lead to unintended issues. Cloudflare Workers run in an execution environment that's neither a full browser nor a complete Node.js runtime. It's a runtime similar to a Service Worker, but very limited in API support: There's no full window object, unlike browsers. Common browser functions like alert, document, localStorage, and others are not available. The global scope behaves more like a Web Worker than a traditional browser tab. If we do something like this: It implies that Cloudflare Workers are browser environments, which isn't true. This might cause issues in the library where code assumes full browser features when isBrowser is true. |
Done a few changes to detect the Cloudflare Worker environment and updated the README with usage instructions. Personally tested, this should work.