Skip to content

Add --init-script option for running scripts before page load - #207

Open
ChrisJr404 wants to merge 1 commit into
simonw:mainfrom
ChrisJr404:init-script-support
Open

ChrisJr404 wants to merge 1 commit into
simonw:mainfrom
ChrisJr404:init-script-support

Conversation

@ChrisJr404

@ChrisJr404 ChrisJr404 commented Aug 18, 2026 •

Copy link
Copy Markdown

This adds a --init-script option that runs JavaScript before the page's own scripts, closing #147.

The existing -j/--javascript option runs code after the page has loaded, but sometimes you need to run something first - to seed Math.random(), freeze Date, or delete navigator.webdriver so a site doesn't detect the headless browser (the news.com.au example in the issue). --init-script registers the code as a Playwright init script, which fires on every navigation before any page scripts run.

I wired it in at the _browser_context() level with context.add_init_script(), so a single implementation covers all of the navigating commands - shot, multi, javascript, accessibility, pdf, html and har - and it naturally applies to every page in the multi command's shared context. The option takes multiple=True so you can register several scripts. Everything is additive and default behaviour is unchanged.

Following the shape of your prototype in fae9bab, though registering at the context level rather than per-page.

Testing: I added three end-to-end tests against the real browser in test_shot_scraper.py - one basic injection, one that proves the script runs before the page's own inline <script> (the page observes the injected value at parse time), and one for multiple --init-script options. The full non-video suite passes locally, and I regenerated the Cog help blocks in the docs (cog --check is clean) plus added a short docs section under javascript.md.


📚 Documentation preview 📚: https://shot-scraper--207.org.readthedocs.build/en/207/

Registers JavaScript as a Playwright init script so it runs on every
navigation before the page's own scripts, useful for seeding Math.random,
freezing Date or hiding navigator.webdriver. Available on shot, multi,
javascript, accessibility, pdf, html and har.

Refs simonw#147

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant