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 JSEvaluationError separately from generic exceptions to distinguish script bugs from pipeline bugs
  • Treat ModuleNotFoundError as a policy signal, not a fatal condition — it often means the input expects a browser API you have chosen not to provide

Common Issues

IssueCauseFix
ModuleNotFoundError on evaluationModule not registeredAdd it to ModuleRegistry or adjust policy
Script failure crashes the pipelineJSEvaluationError not caughtHandle it at the evaluation boundary
Unexpected module accessPolicy too permissiveTighten 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/MethodDescription
JSContextJavaScript evaluation context
ModuleRegistryModule specifier registry
ModuleLoadPolicyModule loading policy control
JSEvaluationErrorTyped script-evaluation failure
ModuleNotFoundErrorTyped missing-module failure

See Also