gramjs icon indicating copy to clipboard operation
gramjs copied to clipboard

Add compatibility for Cloudflare Workers

Open Rohan487 opened this issue 9 months ago • 3 comments

Done a few changes to detect the Cloudflare Worker environment and updated the README with usage instructions. Personally tested, this should work.

Rohan487 avatar Mar 27 '25 08:03 Rohan487

related https://github.com/gram-js/gramjs/issues/506

Rohan487 avatar Mar 27 '25 08:03 Rohan487

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

kubk avatar May 15 '25 05:05 kubk

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: export const isBrowser = isCloudflareWorker || (!isDeno && typeof window !== "undefined");

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.

Rohan487 avatar May 15 '25 06:05 Rohan487