#
Main World Execution
#
Reading the DOM - Isolated World
By default, all JavaScript execution is ran in an isolated scope, invisible to the page.
This makes it impossible for the page to detect JavaScript reading the DOM:
>>> page.goto("https://example.com/")
>>> page.evaluate("document.querySelector('h1').innerText")
'Example Domain'
However, it will not be able to modify the DOM:
>>> page.evaluate("document.querySelector('h1').remove()")
# Will not work!
#
Modifying the DOM - Main World
To be able to modify the DOM, run JavaScript in the main world—the non-isolated scope.
Leak Warning
All code executed in the main world can be detected by the target website. Only execute JavaScript in the main world if absolutely necessary.
To enable main world execution, set the main_world_eval
parameter to True
:
with Camoufox(main_world_eval=True) as browser:
page = browser.new_page()
page.goto("https://example.com/")
Now, you can inject JavaScript in the main world by prefixing the code with mw:
>>> page.evaluate("mw:document.querySelector('h1').remove()")
# h1 is now removed!
You can also return JSON serializable data from the main world:
>>> page.evaluate("mw:{key: 'value'}")
{'key': 'value'}
Note
Returning references to nodes/elements from the main world is not supported, since Playwright's utilities do not run in the main world.
To retrieve node references, use the isolated world instead.