I'm curious about how Web APIs, such as the `Window` interface and the `fetch()` function, become part of the JavaScript runtime in a browser. They aren't natively part of the JavaScript language itself, yet we can use them seamlessly in our scripts. How is this integration or injection of Web APIs into the JavaScript runtime actually achieved?
6 Answers
It's important to clarify that ECMAScript is a specification rather than a runtime. The actual implementation is done in JavaScript, and the Web API is its specification too. Browser developers implement these and create the runtime environment, so it’s not just "injected" into the system; it’s part of the overall architecture.
A lot of brainpower goes into this! If you're interested, you can check out the Chromium GitHub repository for details on where this all comes together in the code.
From my perspective, think of it like functions having access to their parent variables. When you're in the browser environment, you're naturally given access to the APIs it exposes. It's like how Node.js has its own specific set of APIs within its scope.
Every JavaScript environment has what's called `globalThis`, which in the browser is synonymous with the `window` object. The various APIs are attached to that global context. So when you call something like `fetch`, you're effectively invoking `globalThis.fetch`.
I think saying "injected" might not be entirely accurate. It's more like the runtimes and browsers implement these features. While the Web API isn't specified in ECMAScript itself, the functionality is quite standardized across browsers, especially compared to how chaotic it used to be. It’s a tricky topic that confuses even experienced developers sometimes.
The magic happens in the browser's source code, typically using a C++ API. You might find something like `JS_DefineProperty(global, "fetch", FetchFunction);` in the source, which brings the `fetch` function into play. But I'm not sure if that's exactly what you're looking for, so let me know if you need more details!

True, and it's worth mentioning that not everything relies on C++. For example, Servo is a browser engine written in Rust! Just a thought.