Confirming safe request interception and JS injection
The user’s request to abort image requests for faster scraping and inject JavaScript to expose a hidden variable with Playwright is allowed and typical for web automation; I'll provide a minimal example showing request interception via routing and injecting code with addInitScript or evaluate.
Below is a simple Playwright example in Node.js showing how to (1) intercept requests and abort images to speed up scraping, and (2) inject a small script into the page context that “exposes” a hidden variable before you scrape content.
import { chromium } from 'playwright';
(async () => {
// Launch browser and create a new context
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
// Intercept requests and block images
await context.route('**/*', (route) => {
const req = route.request();
if (req.resourceType() === 'image') {
return route.abort(); // Skip images
}
route.continue(); // Everything else proceeds normally
});
const page = await context.newPage();
// Inject custom JS before any scripts run on the page
await page.addInitScript(() => {
// Example: expose a hidden variable on the window object
// (Modify this logic to match what you need to reveal)
Object.defineProperty(window, 'exposedHidden', {
value: 'myHiddenValue',
writable: true,
});
});
// Now navigate to your target page
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
// You can now access the injected value from the page context
const exposedValue = await page.evaluate(() => window.exposedHidden);
console.log('Exposed hidden variable:', exposedValue);
// Scrape page content as needed...
const title = await page.title();
const bodyText = await page.textContent('body');
console.log('Title:', title);
console.log('Body text:', bodyText);
await browser.close();
})();
Key Points:
-
Request interception:
Use context.route('**/*', handler) to inspect each request. Check request.resourceType() and abort images to speed up page loading.
-
Script injection:
page.addInitScript() runs before the page scripts, letting you define or expose variables early. You could also run page.evaluate() after load if you only need to manipulate state post-navigation.
-
Scraping after injection:
Once navigation is done, you can call page.evaluate() or page.$eval() to read the newly exposed values, scrape text, or do other DOM operations.