Chrome Extension 過濾 url 使用 manifest v3

Posted in :

使用 manifest v3 與 v2 用法上有差異,chrome官方的說明:

Migrate to Manifest V3
https://developer.chrome.com/docs/extensions/develop/migrate#modifying-network-requests

Replace blocking web request listeners
https://developer.chrome.com/docs/extensions/develop/migrate/blocking-web-requests

chrome.declarativeNetRequest
https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#type-ResourceType

可以修改用的範例:

chrome.declarativeNetRequest – URL Blocker
https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/api-samples/declarativeNetRequest/url-redirect

心得1是:manifest v3 使用上比 v2 麻煩很多,要多加很多單字,還是指定 ResourceType
https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#type-ResourceType

解法:直接填滿所有 ResourceType:

ENUM

  • “main_frame”
  • “sub_frame”
  • “stylesheet”
  • “script”
  • “image”
  • “font”
  • “object”
  • “xmlhttprequest”
  • “ping”
  • “csp_report”
  • “media”
  • “websocket”
  • “webtransport”
  • “webbundle”
  • “other”

心得2: filter 的 “||” 與 adblock plus 用法不同
https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest

解法2: 用使 * 比較安全。

urlFilterMatchesDoes not match
"abc"https://abcd.com
https://example.com/abcd
https://ab.com
"abc*d"https://abcd.com
https://example.com/abcxyzd
https://abc.com
"||a.example.com"https://a.example.com/
https://b.a.example.com/xyz
https://example.com/
"|https*"https://example.comhttp://example.com/
http://https.com
"example*^123|"https://example.com/123
http://abc.com/example?123
https://example.com/1234
https://abc.com/example0123

一個規則以物件的格式定義,其中有四個屬性:id、priority、action、condition

id:

每個規則需要對應一個id, 不能重覆。

priority:

優先權,數字越大,優先順序越高

action:

如果符合規則,則採取的操作。 有以下四個參數。

type:

必填參數,操作的類型,參數有:

  • “block”(攔截請求)
  • “redirect”(重定向請求)
  • “allow”(允許請求)
  • “upgradeScheme”(升級請求)
  • “modifyHeaders”( 修改請求頭)
  • “allowAllRequests”(允許所有請求)

redirect:
選填,只有操作類型為redirect時才可填,描述應該如何執行重定向。

extensionPath:
相對於擴充目錄的路徑。 以’/’開頭。

regexSubstitution:
指定正規表示式過濾器的規則的替換模式.

url:需要重定向到的網址,不可以重定向到javascript url

transform:url轉換
requestHeaders:選填,只有操作類型為modifyHeaders時才可填,修改請求Headers
responseHeaders:選填,只有操作類型為modifyHeaders時才可填,修改回應Headers

condition:
觸發此規則的條件。 有以下參數,皆為選填參數。

domainType:指定網路請求是發起它的網域的”firstParty”(第一方)還是”thirdParty”(第三方)。 如果省略,則接受所有請求。
domains:符合網域名稱列表,如省略則符合所有網域的請求。
excludedDomains:和domains相反,指定一個排除匹配規則的域名列表,優先級高於domains
requestMethods:http符合請求方法(”get”、”post”等)列表,如省略則符合所有請求方法。
excludedRequestMethods:與requestMethods相反,排除一個請求方法列表,優先權高於requestMethods。
resourceTypes:符合資源類型(”main_frame”、””xmlhttprequest”等)列表,如省略則符合所有請求類型。
excludedResourceTypes:跟resourceTypes相反。
tabIds:符合tabid列表,如省略則符合所有tabs頁。
excludedTabIds:和tabIds相反。
isUrlFilterCaseSensitive:是否區分大小寫,預設為true,區分大小寫
regexFilter:符合網路請求的正規表示式
urlFilter:符合網路請求的url

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *