是否可以使用扩展程序监控Chrome中的HTTP流量?

Pic*_*led 11 javascript google-chrome http google-chrome-extension

我正在尝试编写一个Chrome扩展程序,该扩展程序需要监视HTTP流量以检查是否请求了特定域,然后根据该扩展程序执行其他操作.

如果可能的话,我希望将它全部保留为单个扩展名,因此不能使用Fiddler等.我知道FireFox可以在HttpFox中完成此操作,但我不确定Chrome是否允许这样做.

谢谢.

Jus*_*ris 8

chrome.webRequest很有帮助,但它不允许您在 Chrome 中读取响应正文。

我制作了一个扩展,它使用由内容脚本注入页面的脚本来拦截所有 Web 请求。我的例子在这里: https: //github.com/onhello-automation/onhello/tree/main/app/scripts

我使用/sf/answers/3369388011/来帮助编写此内容,但我纠正了其中的一些问题并简化了它。

一些相关部分:

清单.json

    "content_scripts": [
        {
            "matches": [
                "https://example.com/*"
            ],
            "run_at": "document_start",
            "js": [
                "scripts/content_script.js"
            ]
        }
    ],
    "web_accessible_resources": [
        "scripts/injected.js"
    ],
    "permissions": [
        "https://example.com/*"
    ]
Run Code Online (Sandbox Code Playgroud)

scripts/content_script.ts (我使用webextension-toolbox来构建并将 TypeScript 编译为 JavaScript)

import { browser } from 'webextension-polyfill-ts'

// You can use `browser`/`chrome` here and interact with extension stuff like storage and tabs.

const s = document.createElement('script')
s.src = browser.extension.getURL('scripts/injected.js')
s.onload = async function () {
    (this as any).remove()
};
(document.head || document.documentElement).appendChild(s)
Run Code Online (Sandbox Code Playgroud)

脚本/injected.js:


// You CANNOT use `browser`/`chrome` here and you CANNOT interact with extension stuff like storage and tabs.

const XHR = XMLHttpRequest.prototype

const open = XHR.open
const send = XHR.send
const setRequestHeader = XHR.setRequestHeader

XHR.open = function () {
    this._requestHeaders = {}

    return open.apply(this, arguments)
}

XHR.setRequestHeader = function (header, value) {
    this._requestHeaders[header] = value
    return setRequestHeader.apply(this, arguments)
}

XHR.send = function () {
        
    this.addEventListener('load', function () {
        const url = this.responseURL
        const responseHeaders = this.getAllResponseHeaders()
        try {
            if (this.responseType != 'blob') {
                let responseBody
                if (this.responseType === '' || this.responseType === 'text') {
                    responseBody = JSON.parse(this.responseText)
                } else /* if (this.responseType === 'json') */ {
                    responseBody = this.response
                }
                // Do your stuff HERE.
            }
        } catch (err) {
            console.debug("Error reading or processing response.", err)
        }
    })

    return send.apply(this, arguments)
}
Run Code Online (Sandbox Code Playgroud)


Wal*_*alu 5

也许这就是您正在寻找的: http://code.google.com/chrome/extensions/trunk/experimental.webRequest.html#examples

  • 你会想去这里,因为它不再是实验性的了!https://developer.chrome.com/extensions/webRequest (9认同)