Modyfikowanie nagłówków żądań
Zaimplementuj reguły modyfikowania nagłówków żądań HTTP, umożliwiając niestandardowe działanie lub uwierzytelnianie żądań wychodzących.
Modyfikowanie nagłówków żądań to bezpłatna lekcja Browser Extensions Development (Chrome & Edge) na CoddyKit. To lekcja 2 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.
What are Request Headers?
When your browser talks to a website, it sends messages called HTTP requests. These requests carry extra info, like metadata, in something called headers.
Headers tell the server things like what browser you're using (User-Agent), what kind of content you expect (Accept), or even authentication tokens (Authorization).
Efficient Header Control
We learned about declarativeNetRequest for blocking and redirecting. It's powerful because it lets the browser handle rules efficiently, without your extension's JavaScript always running.
Today, we'll use it to modify these request headers, adding, changing, or removing them before a request even leaves your browser!
Introducing `modifyHeaders`
To change headers, we use a specific actionType within our declarativeNetRequest rules: "modifyHeaders".
This action takes an array of requestHeaders. Each item in this array describes a single header modification you want to make.
Header Operations Explained
For each header modification, you specify an operation:
"set": Replaces an existing header's value or adds it if it doesn't exist."append": Adds a new value to a header. If the header already exists, it will have multiple values. If not, it adds it."remove": Deletes a header entirely from the request.
Essential Permissions
To use declarativeNetRequest for header modification, your extension needs specific permissions in its manifest.json file:
"declarativeNetRequest": The basic permission to use the API."declarativeNetRequestWithHostAccess": Needed if your rules modify headers on specific websites (hosts). This is usually the case!
Add a Custom Header
Let's add a custom header called X-CoddyKit-User to all outgoing requests. This could be useful for identifying requests from your extension.
This code goes into your extension's background.js file.
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [1],
addRules: [{
id: 1,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: [{
header: "X-CoddyKit-User",
operation: "set",
value: "CoddyKitStudent"
}]
},
condition: {
urlFilter: "<all_urls>",
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest"]
}
}]
});
// In a real extension, this runs once on install/update.
// You'd observe the header in your browser's DevTools Network tab.Dissecting the Rule
The code uses chrome.declarativeNetRequest.updateDynamicRules to manage rules. Here's a quick breakdown:
id: A unique number for your rule.priority: Determines which rule wins if multiple rules apply.action: Defines what to do. Here,"modifyHeaders"with ourrequestHeaders.condition: Specifies when the rule applies (e.g.,<all_urls>for everywhere).
Change the User-Agent
You can use "set" to change standard headers too. Here, we'll modify the User-Agent header for requests going to example.com. This spoofs your browser's identity for that site.
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [2],
addRules: [{
id: 2,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: [{
header: "User-Agent",
operation: "set",
value: "CoddyKitBrowser/1.0 (Extension)"
}]
},
condition: {
urlFilter: "*://example.com/*",
resourceTypes: ["main_frame", "sub_frame"]
}
}]
});
// This rule would change the User-Agent for example.com.Remove a Header
Sometimes, you might want to remove a header for privacy or to prevent certain tracking. Let's remove the Referer header for all image requests.
The Referer header tells a website where you came from.
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [3],
addRules: [{
id: 3,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: [{
header: "Referer",
operation: "remove"
}]
},
condition: {
urlFilter: "<all_urls>",
resourceTypes: ["image"]
}
}]
});
// This rule would remove the Referer header for image requests.Quick Check: Header Operations
You want to add an API key as a custom header, X-API-Key, to a request. If the header somehow already exists, you want to make sure your key is also present, possibly as a second value, rather than replacing an existing one.
Recap & Next Steps
Great job! You've learned how to powerfully modify HTTP request headers using declarativeNetRequest.
- We explored the
"modifyHeaders"action. - Understood the
"set","append", and"remove"operations. - Saw how to add custom headers, change user agents, and remove sensitive info.
- Remember the necessary permissions:
declarativeNetRequestanddeclarativeNetRequestWithHostAccess.
Next, we'll dive into redirecting and rewriting URLs!
Często zadawane pytania
Czy lekcja „Modyfikowanie nagłówków żądań” jest bezpłatna?
Tak — pełny tekst „Modyfikowanie nagłówków żądań” 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 „Modyfikowanie nagłówków żądań”?
Zaimplementuj reguły modyfikowania nagłówków żądań HTTP, umożliwiając niestandardowe działanie lub uwierzytelnianie żądań wychodzących. Ć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 2 z 4.
Ile czasu zajmuje lekcja „Modyfikowanie nagłówków żądań”?
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