0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Manifest V3 の declarativeNetRequest API を用いた最小構成のChrome拡張機能を自作した

Last updated at Posted at 2025-12-27

はじめに

特定のURLにアクセスした際、自動的に別のURL(パラメータ付き等)へリダイレクトさせたいことが発生した。
Manifest V3 の declarativeNetRequest API を使用した最小構成のChrome拡張機能を自作したので備忘録として残しておく。

declarativeNetRequest API について

Manifest V3 では、ネットワークリクエストの制御に declarativeNetRequest API が推奨されている。
従来の webRequest API(ブロッキング)と比較して以下のメリットがある。

  • JavaScript不要: JSON を定義するだけで動作し Service Worker を常駐させる必要がない
  • パフォーマンス: ブラウザのネットワークスタック内で処理されるため高速
  • プライバシー: 拡張機能側でリクエスト内容を読み取る必要がない

今回は単純なリダイレクトのみが必要なため、このAPIを採用した。

実装

ファイルは manifest.jsonrules.json の2つだけ。

1. manifest.json

拡張機能の定義ファイル。
declarative_net_request キーでルールファイルを指定する。

manifest.json
{
  "name": "Sample Chrome Extension",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "declarativeNetRequest"
  ],
  "host_permissions": [
    "*://*.example.com/*"
  ],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules.json"
      }
    ]
  }
}

2. rules.json

リダイレクトルールを記述。
以下は example.com のトップページにアクセスした際、example.org へリダイレクトする設定です。

rules.json
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://example.org"
      }
    },
    "condition": {
      "regexFilter": "^https?://(www\\.)?example\\.com/?$",
      "resourceTypes": [
        "main_frame"
      ]
    }
  }
]

ちなみに、単純にホスト名だけでマッチさせると、リダイレクト先や下層ページでもルールが適用され、無限ループに陥る可能性がある。
regexFilter の末尾に $を指定し、「トップページへの完全一致」のみを対象とした。これにより、クエリパラメータ付きのURLや下層パスへのアクセスを除外し、意図しないループを防いでいる。

おわりに

Manifest V3 の declarativeNetRequest API を使用することで、非常に少ないコード量で安全にリクエスト制御を行うことができら。
導線制御や、特定のパラメータ付与などに応用できるため、ぜひ試してみてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?