Blokowanie żądań sieciowych
Dowiedz się, jak definiować reguły blokowania niepożądanych żądań sieciowych, takich jak reklamy lub skrypty śledzące, za pomocą `declarativeNetRequest`.
Blokowanie żądań sieciowych to bezpłatna lekcja Browser Extensions Development (Chrome & Edge) na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Browser Extensions Development (Chrome & Edge), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Browser Extensions Development (Chrome & Edge) zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Intro to Blocking Requests
Welcome to modifying web requests! This lesson introduces declarativeNetRequest, a powerful API for controlling network requests in your browser extension.
You'll learn how to define rules to block unwanted content like ads, tracking scripts, or specific resources, making web browsing cleaner and faster.
Why Block Network Requests?
Blocking network requests isn't just about privacy; it's also about performance and user experience.
- Remove Ads: Block requests to ad servers.
- Stop Trackers: Prevent tracking scripts from loading.
- Improve Performance: Less data downloaded means faster page loads.
- Enhance Security: Block malicious domains or content.
Declarative vs. Imperative
Traditional ad blockers often use imperative logic: JavaScript code that runs on every page to detect and block elements.
declarativeNetRequest is declarative. You define rules, and the browser handles the blocking efficiently, often without waking up your extension's JavaScript. This is faster and more resource-friendly!
Manifest Permission for Blocking
To use declarativeNetRequest, your extension needs to declare the permission in its manifest.json file.
This tells the browser your extension intends to modify network requests.
{
"manifest_version": 3,
"name": "My Blocker",
"version": "1.0",
"permissions": [
"declarativeNetRequest"
]
}Structure of a Blocking Rule
A blocking rule is an object with an id, an action, and a condition. The browser checks these conditions against every network request.
id: A unique number for the rule.action: What to do (e.g., 'block', 'redirect').condition: When to apply the action (e.g., 'urlFilter', 'resourceTypes').
The 'Block' Action Type
For this lesson, we'll focus on the "block" action. When a request matches a rule with this action, the browser simply prevents that request from completing.
The action part of your rule will look like this:
{
"action": {
"type": "block"
}
}Conditions: `urlFilter`
The urlFilter property in a rule's condition allows you to specify a pattern for URLs to match. It's like a mini-regex.
"*://*.example.com/*"matches any subdomain of example.com."*://ads.google.com/*"specifically targets Google ads."*track*"matches URLs containing 'track'.
Conditions: `resourceTypes`
You can also specify which types of resources to block using resourceTypes. This helps you target specific content like images, scripts, or fonts.
Common types include "script", "image", "stylesheet", "media", and "font".
Adding Dynamic Blocking Rules
Rules can be added dynamically by your extension using chrome.declarativeNetRequest.updateDynamicRules(). This is often done in your background script.
This example adds a rule to block requests containing "adserver" in their URL, specifically for scripts and images.
console.log("Background script running.");
const BLOCK_RULE_ID = 1;
chrome.runtime.onInstalled.addListener(() => {
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [BLOCK_RULE_ID], // Remove if already exists
addRules: [{
id: BLOCK_RULE_ID,
priority: 1,
action: { type: "block" },
condition: {
urlFilter: "*://*adserver*/*",
resourceTypes: ["script", "image"]
}
}]
}, () => {
if (chrome.runtime.lastError) {
console.error("Error updating rules: ", chrome.runtime.lastError);
} else {
console.log("Blocking rule added!");
}
});
});
// To test, visit a page with 'adserver' in script/image URLs.Quick Check: Rule Matching
Consider the following blocking rule:
{
"id": 2,
"priority": 1,
"action": { "type": "block" },
"condition": {
"urlFilter": "*://*.tracker.com/*",
"resourceTypes": ["script", "image"]
}
}Which of these requests would be blocked?
Recap: Blocking Requests
Great job! You've learned the basics of blocking network requests with declarativeNetRequest.
- It's a powerful, performant, and privacy-friendly API.
- Rules consist of an
id,action(e.g.,"block"), andcondition. urlFilterandresourceTypesare key for defining conditions.- Dynamic rules can be added and managed using
updateDynamicRules().
Next, you'll explore modifying headers!
Często zadawane pytania
Czy lekcja „Blokowanie żądań sieciowych” jest bezpłatna?
Tak — pełny tekst „Blokowanie żądań sieciowych” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Browser Extensions Development (Chrome & Edge), przejdź na CoddyKit PRO. Kurs Browser Extensions Development (Chrome & Edge) zawiera 4 lekcji w sumie.
Co nauczysz się w „Blokowanie żądań sieciowych”?
Dowiedz się, jak definiować reguły blokowania niepożądanych żądań sieciowych, takich jak reklamy lub skrypty śledzące, za pomocą `declarativeNetRequest`. Ćwiczysz Browser Extensions Development (Chrome & Edge) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Browser Extensions Development (Chrome & Edge)?
Nie wymagamy żadnego doświadczenia. Browser Extensions Development (Chrome & Edge) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.
Ile czasu zajmuje lekcja „Blokowanie żądań sieciowych”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Browser Extensions Development (Chrome & Edge)?
Tak. Każda lekcja Browser Extensions Development (Chrome & Edge) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Blokowanie żądań sieciowych
- Modyfikowanie nagłówków żądań
- Przekierowywanie i przepisywanie adresów URL
- Dynamiczne reguły i debugowanie declarativeNetRequest