JavaScript Context
JavaScript Context
The scripting layer provides a controlled JavaScript evaluation context for documents that need one. It is deliberately policy-driven: module resolution is explicit, and failures surface as typed exceptions.
The Evaluation Context
JSContext hosts script evaluation. Errors raised during evaluation surface as JSEvaluationError, keeping script failures distinct from Python-side errors.
Module Loading
Module resolution is governed by ModuleRegistry, which maps module specifiers to implementations. Missing modules raise ModuleNotFoundError (the library’s own typed error) rather than silently returning stubs.
Load Policies
ModuleLoadPolicy controls what a context is allowed to load — the mechanism for sandboxing script behaviour in server-side processing where arbitrary module access is unwanted.
Tips and Best Practices
- Register only the modules your processing scenario needs; a small registry is the sandbox
- Catch
JSEvaluationErrorseparately from generic exceptions to distinguish script bugs from pipeline bugs - Treat
ModuleNotFoundErroras a policy signal, not a fatal condition — it often means the input expects a browser API you have chosen not to provide
Common Issues
| Issue | Cause | Fix |
|---|---|---|
ModuleNotFoundError on evaluation | Module not registered | Add it to ModuleRegistry or adjust policy |
| Script failure crashes the pipeline | JSEvaluationError not caught | Handle it at the evaluation boundary |
| Unexpected module access | Policy too permissive | Tighten ModuleLoadPolicy |
FAQ
Is script evaluation required for parsing?
No — parsing, CSSOM, and layout work without any script context.
How do I control what scripts can import?
Through ModuleRegistry (what exists) and ModuleLoadPolicy (what may load).
How do script errors surface?
As JSEvaluationError exceptions on the Python side.
API Reference Summary
| Class/Method | Description |
|---|---|
JSContext | JavaScript evaluation context |
ModuleRegistry | Module specifier registry |
ModuleLoadPolicy | Module loading policy control |
JSEvaluationError | Typed script-evaluation failure |
ModuleNotFoundError | Typed missing-module failure |