-
Notifications
You must be signed in to change notification settings - Fork 311
Intercept and block requests by URL
wad-jet.ru edited this page Feb 26, 2018
·
4 revisions
Load a page blocking requests that match .css
, .png
or .svg
.
(This requires Chrome >= 61)
const CDP = require('chrome-remote-interface');
const url = require('url');
function shallNotPass(request) {
const {pathname} = url.parse(request.url);
return pathname.match(/\.(css|png|svg)$/);
}
CDP(async (client) => {
const {Network, Page} = client;
// catch request
Network.requestIntercepted(({interceptionId, request}) => {
// perform a test against the intercepted request
const blocked = shallNotPass(request);
console.log(`- ${blocked ? 'BLOCK' : 'ALLOW'} ${request.url}`);
// decide whether allow or block the request
Network.continueInterceptedRequest({
interceptionId,
errorReason: blocked ? 'Aborted' : undefined
});
});
try {
// enable domains
await Network.enable();
await Page.enable();
// enable request interception
await Network.setRequestInterception({ patterns: [{ urlPattern: '*' }] });
// disable cache
await Network.setCacheDisabled({cacheDisabled: true});
// navigate to URL and wait for termination
await Page.navigate({url: 'https://github.com'});
await Page.loadEventFired();
} catch (err) {
console.error(err);
} finally {
client.close();
}
}).on('error', (err) => {
console.error(err);
});