Pages, styles and blocking
Change matching pages, exchange messages and filter unwanted resources.
Developer preview · macOS · Python SDK 1.1Read or change a loaded page
from browse import on
@on.page_load(match="*://example.com/*")
async def comfortable_reading(page):
await page.inject_css("body { line-height: 1.7; }")
title = await page.eval("document.title")
print(title)| Call | Effect |
|---|---|
| await page.eval(script) | Evaluate JavaScript and return its last value, converted to Python. |
| await page.inject_js(script) / page.inject_css(css) | Run a script or insert CSS. |
| await page.text() | Read the page’s body text. |
| await page.post(value) | Send a JSON-compatible message to your page script. |
Page scripts share the document with the website but run in the extension’s isolated JavaScript world. They do not share the page’s JavaScript variables or other extensions’ worlds. If a page navigates outside your permitted sites during evaluation, Browse withholds the result.
Register styles for future loads
from browse import styles
style_id = styles.register(
"*://news.ycombinator.com/*",
css="body { background: #fff0f6 !important; }",
run_at="start",
)
# Later: styles.unregister(style_id)styles.register accepts a match pattern or list, css and/or js, and run_at="start" or "end". Registration can happen at import time. unregister stops future injections; pages already showing the style keep it until reloaded. There is a limit of 100 registrations per extension. Styles and page scripts apply to the main frame only.
Exchange messages with a page
from browse import on, styles
styles.register(
"*://example.com/*",
js="""
browse.onMessage(value => console.log(value));
browse.postMessage({title: document.title});
""",
run_at="end",
)
@on.message(match="*://example.com/*")
async def received(message, page):
print(message)
await page.post({"received": True})Block resources or hide elements
from browse import rules
rules.block("*.doubleclick.net", types=["script", "image"], on=["example.com"])
rules.hide(".cookie-banner", on=["example.com"])
# Remove this extension's registered rules: rules.clear()Blocking rules are applied by the browser’s content blocker without calling Python for each resource. Use host patterns for blocked hosts and on sites. Hiding needs pages permission for the affected sites; omitting on applies everywhere and requires broad permission.
Resource types are document, image, style-sheet, script, font, raw, svg-document, media and popup. Omit types to cover all supported types. Each extension can register up to 500 rules.