0Pricing
Browser Extensions Development (Chrome & Edge) · レッスン

ネットワーク リクエストのブロック

`declarativeNetRequest`を使って、広告やトラッキングスクリプトなど、不要なネットワーク リクエストをブロックするルールを定義します。

「ネットワーク リクエストのブロック」はCoddyKit上の無料Browser Extensions Development (Chrome & Edge)レッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはBrowser Extensions Development (Chrome & Edge)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Browser Extensions Development (Chrome & Edge)コースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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"), and condition.
  • urlFilter and resourceTypes are key for defining conditions.
  • Dynamic rules can be added and managed using updateDynamicRules().

Next, you'll explore modifying headers!

よくある質問

「ネットワーク リクエストのブロック」レッスンは無料ですか?

はい。「ネットワーク リクエストのブロック」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Browser Extensions Development (Chrome & Edge)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Browser Extensions Development (Chrome & Edge)コースには全4レッスンが含まれています。

「ネットワーク リクエストのブロック」で何を学びますか?

`declarativeNetRequest`を使って、広告やトラッキングスクリプトなど、不要なネットワーク リクエストをブロックするルールを定義します。 ブラウザで直接実行するハンズオンコードでBrowser Extensions Development (Chrome & Edge)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Browser Extensions Development (Chrome & Edge)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのBrowser Extensions Development (Chrome & Edge)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「ネットワーク リクエストのブロック」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このBrowser Extensions Development (Chrome & Edge)レッスンでコードを書いて実行できますか?

はい。すべてのBrowser Extensions Development (Chrome & Edge)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ネットワーク リクエストのブロック
  2. リクエストヘッダーの変更
  3. URLのリダイレクトと書き換え
  4. 動的ルールとdeclarativeNetRequestのデバッグ
← Browser Extensions Development (Chrome & Edge)に戻る