🛑 Why Block Assets in Automation?
During automated end-to-end testing, browsers spend substantial network bandwidth and CPU cycles downloading heavyweight media assets (PNG/JPEG/WebP images, SVG sprites, custom WOFF2 typography, and video clips) as well as waiting for external analytics trackers (Google Analytics, Hotjar, Segment). For functional and business-logic tests, these external dependencies add zero testing value while significantly inflating execution runtimes and introducing intermittent flakiness on CI/CD pipelines. Playwright enables fine-grained resource blocking via page.route() and route.abort(). By aborting unnecessary requests at the network socket layer, pages load up to 300% faster while conserving data limits on containerized build runners.
request.resource_type string. This allows engineers to drop entire categories of assets with sub-millisecond precision.
PLAYWRIGHT RESOURCE CLASSIFICATIONS (request.resource_type):
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────┐
│ Resource Type │ Typical Extensions │ Default Testing Recommendation │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────┤
│ "document" │ .html, .php, / │ DO NOT BLOCK (Primary HTML skeleton) │
│ "script" │ .js, .mjs, .ts │ KEEP (Powers application logic & SPAs) │
│ "stylesheet" │ .css │ KEEP (Maintains layout & visibility) │
│ "image" │ .png, .jpg, .svg, .webp │ BLOCK (Heavy payload; rarely functional)│
│ "font" │ .woff, .woff2, .ttf, .otf │ BLOCK (Eliminates layout shift delays) │
│ "media" │ .mp4, .webm, .mp3, .ogg │ BLOCK (High bandwidth consumption) │
│ "ping" / "beacon" │ /analytics, /collect, /log │ BLOCK (Third-party tracking telemetry) │
│ "eventsource" / "websocket" │ wss://, /sse │ KEEP (Real-time application sync) │
└──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────┘
image, while letting HTML, JavaScript, and styles load uninterrupted.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
blocked_images = []
def block_images(route):
if route.request.resource_type == "image":
blocked_images.append(route.request.url)
# Abort request immediately before connection is opened
route.abort()
else:
route.continue_()
# Route pattern catches all URLs across the page
page.route("**/*", block_images)
page.set_content("""
Catalog Products
Product Descriptions Loaded Instantly
""")
expect(page.locator("p")).to_have_text("Product Descriptions Loaded Instantly")
print(f"Total Blocked Image Requests: {len(blocked_images)}")
for url in blocked_images:
print(f" Blocked: {url}")
browser.close()
set lookup to create a comprehensive bandwidth-saving filter for content-heavy sites.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
BLOCKED_TYPES = {"image", "font", "media"}
blocked_count = 0
def asset_filter(route):
nonlocal blocked_count
if route.request.resource_type in BLOCKED_TYPES:
blocked_count += 1
route.abort("blockedbyclient")
else:
route.continue_()
page.route("**/*", asset_filter)
page.goto("https://quotes.toscrape.com/")
print(f"Successfully Loaded Page : '{page.title()}'")
print(f"Total Non-Essential Assets Blocked: {blocked_count}")
print("Page executed with maximum network efficiency.")
browser.close()
.png, .jpg, .woff2, or .mp4) directly in the route registration pattern without writing manual conditionals.
import re
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Pattern A: Playwright Glob pattern for images
page.route("**/*.{png,jpg,jpeg,webp,gif}", lambda route: route.abort())
# Pattern B: Python compiled Regular Expression for custom fonts
font_regex = re.compile(r".*\.(woff|woff2|ttf|otf|eot)(\?.*)?$")
page.route(font_regex, lambda route: route.abort())
page.goto("https://demo.playwright.dev/todomvc/")
print("Registered direct extension abort handlers.")
print(f"Page Title Verified: '{page.title()}'")
browser.close()
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
TRACKING_DOMAINS = [
"google-analytics.com",
"googletagmanager.com",
"connect.facebook.net",
"segment.io",
"hotjar.com",
"doubleclick.net"
]
intercepted_trackers = []
def block_analytics(route):
url = route.request.url
if any(domain in url for domain in TRACKING_DOMAINS):
intercepted_trackers.append(url)
route.abort("blockedbyclient")
else:
route.continue_()
# Intercept all outbound requests
page.route("**/*", block_analytics)
page.set_content("""
Enterprise Portal
""")
print(f"Total Analytics Trackers Intercepted & Blocked: {len(intercepted_trackers)}")
for t_url in intercepted_trackers:
print(f" Dropped: {t_url[:65]}...")
browser.close()
route.abort(error_code=...) to simulate specific network failures (such as server timeouts, DNS failures, or adblock client interventions).
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# 1. Simulate client-side ad blocker intervention
page.route("**/telemetry", lambda route: route.abort("blockedbyclient"))
# 2. Simulate raw network socket timeout
page.route("**/slow-external-service", lambda route: route.abort("timedout"))
# 3. Simulate DNS lookup or connection failure
page.route("**/unreachable-host", lambda route: route.abort("connectionfailed"))
page.set_content("""
Ready
""")
page.locator("#test-timeout").click()
page.wait_for_timeout(300)
print(f"Client UI Error Response Captured: '{page.locator('#out').inner_text()}'")
browser.close()
context.route() to ensure every tab, popup window, and embedded iframe inherits the blocking policy automatically without configuring each page individually.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
# Apply asset blocking globally across the entire BrowserContext
context.route("**/*.{png,jpg,jpeg,svg,webp}", lambda route: route.abort())
context.route("**/*.woff2", lambda route: route.abort())
# Tab 1: Automatically inherits asset blocking
tab1 = context.new_page()
tab1.goto("https://demo.playwright.dev/todomvc/")
print(f"Tab 1 Loaded (Assets Blocked): '{tab1.title()}'")
# Tab 2: Also inherits asset blocking seamlessly
tab2 = context.new_page()
tab2.goto("https://example.com")
print(f"Tab 2 Loaded (Assets Blocked): '{tab2.title()}'")
context.close()
browser.close()
conftest.py fixture to accelerate execution across your entire test suite automatically.
# content of conftest.py
import pytest
from playwright.sync_api import Page
BLOCKED_RESOURCES = {"image", "media", "font"}
@pytest.fixture(autouse=True)
def speed_up_tests_by_blocking_assets(page: Page):
"""Automatically blocks non-essential media assets across all Pytest test cases."""
def block_unneeded_assets(route):
if route.request.resource_type in BLOCKED_RESOURCES:
route.abort()
else:
route.continue_()
page.route("**/*", block_unneeded_assets)
yield
# Routes are automatically cleared on page teardown
# content of test_inventory.py
def test_dashboard_workflow(page: Page):
page.goto("https://demo.playwright.dev/todomvc/")
# Test executes with all heavy media assets automatically blocked!
page.get_by_placeholder("What needs to be done?").fill("Verify Speed Boost")
page.get_by_placeholder("What needs to be done?").press("Enter")
onload event to avoid rendering broken placeholder borders, replace heavy images with a lightweight 1x1 transparent GIF data URI instead of aborting.
import base64
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# 1x1 transparent GIF byte sequence (43 bytes total)
TINY_1X1_GIF = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
def substitute_lightweight_image(route):
if route.request.resource_type == "image":
# Return valid 1x1 pixel: triggers onload without downloading megabytes
route.fulfill(
status=200,
content_type="image/gif",
body=TINY_1X1_GIF
)
else:
route.continue_()
page.route("**/*", substitute_lightweight_image)
page.set_content("""
Waiting for load...
""")
status = page.locator("#load-status")
expect(status).to_have_text("IMAGE_ONLOAD_FIRED")
print(f"Verified image substitution: '{status.inner_text()}' (Onload event triggered!)")
browser.close()
PLAYWRIGHT ASSET BLOCKING & FILTERING API MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Method / Property │ Return Type / Arguments │ Description / Primary Use Case │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ request.resource_type │ str │ Identifies asset type: "image", "font", "script", etc. │
│ route.abort(error_code=...) │ error_code: Optional[str] │ Aborts request at socket layer. Default: "failed". │
│ route.continue_() │ kwargs │ Permits request to proceed upstream to real server. │
│ page.route(pattern, handler) │ url: str / Regex, handler │ Scopes asset blocking rule to single Page instance. │
│ context.route(pattern, ...) │ url: str / Regex, handler │ Scopes asset blocking across all pages in the context. │
│ page.unroute(pattern) │ url: str / Regex │ Removes active asset blocking rule. │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ SUPPORTED ABORT ERROR CODES: │
│ * "blockedbyclient" ──► Simulates an active browser extension / ad-blocker dropping the call. │
│ * "timedout" ──► Simulates a connection timeout where server fails to respond. │
│ * "connectionfailed" ──► Simulates a network-level disconnection / server down error. │
│ * "connectionreset" ──► Simulates TCP RST packet resetting connection mid-flight. │
│ * "accessdenied" ──► Simulates OS or proxy socket permission denials. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘