Implementation of chrome request filtering extension

XXHolic 2021-05-03 21:28:12
implementation chrome request filtering extension


next Chrome Expand : introduction , Next, start to realize what you thought at the beginning : Network request filtering . In short, it is to listen to all requests of a website , Show the request you want in the extension . extension Capture Request .

Demand concretization

The idea above is rather vague , In order to achieve this goal , Combined with an example of documentation , What we have to do is :

  1. Extension should have corresponding icon and prompt .
  2. Click the toolbar extension icon , Open a new Tab page , Used to display information about the request .
  3. Extended listening is active Tab Website request for , You can configure the web address for filtering and monitoring .
  4. Requests for listening , Support according to url Filter and export .

Some functions are not easy to find directly in the document , This is the time , It is suggested that Chrome The store is looking for an open source extension , According to the effect, there are some API , Then find the corresponding document . Here's a reference FeHelper Some of the implementations . It should be noted that FeHelper Based on Development manifest_version Version is 2 , The following development extensions are based on the recommended version of 3 , For the full code, see Capture Request .


Icon related information configuration

according to introduction The information in it , Where icons might appear are toolbars 、 Expand the management page 、 Permission warnings and favicon On , stay manifest.json The following related fields configured in :

"name": "Capture Request",
"description": "Capture Request",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_icon": {
"16": "xxx.png",
"32": "xxx.png",
"16": "xxx.png",
"32": "xxx.png",
 Copy code 

A detailed description of what size icon should be used in here , The document recommends PNG Picture format for . Follow this , I found that some icons are too small to look blurry , You can also use larger sizes ,Chrome Will compress the image to the required size .

Click extend to open a new Tab page

stay introduction The display form of click expansion inside is to open a pop-up window , In the document Design the user interface In the form of Popup 、Tooltip、Omnibox、Context menu、Override pages , Most likely Override pages , But I tried it and it didn't work , So I went to see the realization of others , Discovery can be done by monitoring Click on the icon event Open new Tab .

But it seems that it can be used directly API , In fact, there are the following points to consider :

  1. Where to monitor this incident ?
  2. When to monitor this incident ?
  3. How to open a new Tab ?
  4. Do you need permission , if necessary , Involving those authorities ?

stay introduction The function is added through Background script , I think it's very important at the beginning of the document :

Extensions are changed or enhanced by event based programming Chrome Browsing experience .

You can see from the documentation that , In the background script, we can solve the problem mentioned above 1、2 Two questions , The authority required is scripting .

open Tab The use of API yes chrome.tabs , The authority required is tabs .

The main approach is to manifest.json Add the following configuration :

+ "permissions": [
+ "scripting",
+ "tabs",
+ ],
+ "background": {
+ "service_worker": "background.js"
+ },
 Copy code 

Then create a new background script file background.js , And add the following main logic code :

chrome.action.onClicked.addListener(() => {
url: 'page.html'
 Copy code 

Monitoring requests and configuration

To activate Tab Requests from the website are displayed on the open extension page , The main points to consider are :

  1. How to find the active Tab ?
  2. How to intercept a web request ?
  3. How to synchronize the intercepted request to the extended custom page ?

Open it from above Tab To achieve the effect of , It can be associated with API It should be there, too chrome.tabs in , Discovery provides query Methods can solve the problem of 1 A question .

The way to intercept requests is through online search , Find documents chrome.webRequest , It describes in detail the life cycle of the request in the extension and the events triggered , After comparative thinking , The individual finally decided to monitor onResponseStarted event , The authority required is webRequest . This solves the problem of 2 A question .

reference introduction The way the color changes inside , Similarly, you can cache requests to , Then get... On the extended page , The authority required is storage . About data synchronization , By monitoring Events get the latest data on changes . This solves the problem of 3 A question .

During commissioning , Found local data usage when , After the request reaches a certain amount , Will report a mistake . Looking at the document, I found that the maximum value of this method is limited , It's not suitable for storing a large amount of request data , Use More appropriate .

You can configure filtering requests directly by introduction The configuration inside is handled in the same way , But one thing to note is , Whenever the configuration is updated , It needs to be monitored again onResponseStarted event .

The main approach is to manifest.json Of permissions Field webRequeststorage .

stay background.js Add the main code to :

// Store request data default 
let requestList = []
// The default value of URL filtering 
let urlPattern = '<all_urls>'
// The handler that listens to the request event 
const handlerResponseStarted = (details) => {
// Find the active Tab
chrome.tabs.query({ active: true }, (tab) => {
requestList.unshift(details){ requestList });
return { cancel: true };
// monitor storage Change events, areaName) => {
const { urlPattern } = changeObj
// Because in page.html It's also monitored , So we have to judge whether it is urlPattern It's changed 
if (areaName !== 'local' || !urlPattern) {
console.warn('urlPattern does not change')
const { newValue } = urlPattern
const hasAddListen = chrome.webRequest.onResponseStarted.hasListener(handlerResponseStarted)
if (hasAddListen) {
{ urls: [newValue] },
 Copy code 

To expand the page page.html Add script file pages.js , Add key logic :, areaName) => {
const { requestList } = changeObj
// Because in background.js It's also monitored , So we have to judge whether it is requestList It's changed 
if (areaName !== 'local' || !requestList) {
console.warn('requestList does not change')
const { newValue } = requestList || { newValue: [] }
const newItem = newValue[0] || null
if (!newItem) {
console.warn('no data')
// Logic of displaying data 
 Copy code 

Derived data

Intercepted the data you want , There is a need to export to a local scenario , Reference resources FeHelper The realization inside , Found the document chrome.downloads , The authority required is downloads .

The main approach is to manifest.json Of permissions Field downloads .

stay pages.js Add key logic :

 let localFilterList = []; // Page filtered data 
// Click the Export button 
const exportEle = document.querySelector('#operate-export')
exportEle.addEventListener('click', () => {
if (!localFilterList.length) {
alert(' No valid data ')
const txt = JSON.stringify(localFilterList)
let blob = new Blob([txt], { type: 'application/octet-stream' });
// The number of seconds the file name was retrieved , You can define it according to your own preference 
let dt = (new Date()).getSeconds();{
url: URL.createObjectURL(blob),
saveAs: true,
conflictAction: 'overwrite',
filename: dt + '.json'
 Copy code 

Reference material


Recently I watched a TV play 《 A Town Besieged 》, Although it's very early , But it's really interesting , It is said that it was shot completely according to the original work , There's no adaptation .

In the last paragraph of the novel is about marriage besieged city , I don't know when to start , I always thought the whole book was about the siege of marriage .



  1. Analysis of MVC
  2. [middle stage] please stay and join me in the backstage
  3. Understanding front end garbage collection
  4. [continuous update] front end special style implementation
  5. Flutter product analysis and package reduction scheme
  6. XPath positioning
  7. 前端开发css中的flex布局的使用
  8. The use of flex layout in front end development CSS
  9. JQuery核心函数和静态方法
  10. JQuery core functions and static methods
  11. Node family - understanding of blocking and non blocking
  12. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  13. Vue source code analysis (2) initproxy initialization proxy
  14. What's TM called react diff
  15. Summary of common front end data structure
  16. Useeffect in hooks
  17. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  18. Front end notes: virtual Dom and diff of vue2. X
  19. The best code scanning plug-in of flutter
  20. The simplest plug-in for rights management of flutter
  21. 21. Object oriented foundation "problems and solutions of object traversal"
  22. Discussion on hot micro front end: Google AdWords is a real micro front end
  23. Usecallback and usememo for real performance optimization
  24. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  25. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  26. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  27. Transaction of spring's reactive / imperative relational database
  28. The implementation of hexagonal hexagonal reactjs Janos pasztor
  29. HTTP状态码:402 Payment Required需要付款 - mozilla
  30. HTTP status code: 402 payment required - Mozilla
  31. Factory mode, constructor mode and prototype mode
  32. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  33. Cocos Quick Start Guide
  34. Comparison of three default configurations of webpack5 modes
  35. A case study of the combination of flutter WebView and Vue
  36. CSS: BFC and IFC
  37. A common error report and solution in Vue combat
  38. JS: this point
  39. JS: prototype chain
  40. JavaScript series -- promise, generator, async and await
  41. JS: event flow
  42. Front end performance optimization: rearrangement and redrawing
  43. JS - deep and shallow copy
  44. JavaScript异步编程3——Promise的链式使用
  45. JavaScript asynchronous programming 3 -- chain use of promise
  46. Vue.js组件的使用
  47. The use of vue.js component
  48. How to judge whether a linked list has links
  49. Element UI custom theme configuration
  50. Text image parallax effect HTML + CSS + JS
  51. Spring的nohttp宣言:消灭http://
  52. Vue3 intermediate guide - composition API
  53. Analysis of URL
  54. These 10 widgets that every developer must know
  55. Spring's nohttp Manifesto: eliminate http://
  56. Learn more about JS prototypes
  57. Refer to await to JS to write an await error handling
  58. A short article will directly let you understand what the event loop mechanism is
  59. Vue3 uses mitt for component communication
  60. Characteristics and thinking of ES6 symbol