首页 > 解决方案 > 如何在 Firefox 扩展中捕获特定的 xmlhttprequests?

问题描述

我正在编写一个 firefox 扩展程序,并希望捕获发送到某个 url 的请求。

我正在browser.webRequest.onCompleted从后台脚本向事件添加一个侦听器。<all_urls>问题是,只有当我添加清单的权限部分和添加侦听器时过滤器中的 urls 选项时,侦听器才会被触发。

src/background.js:

function saveData(result) {
    console.log(result);
}

browser.webRequest.onCompleted.addListener(
    saveData,
    {
        urls: ["<all_urls>"],
        types: ['xmlhttprequest']
    });

清单.json:

{
    "manifest_version": 2,
    "name": "LolEsports Extension",
    "version": "1.0.0",

    "permissions": [
        "<all_urls>",
        "webRequest",
        "webRequestBlocking",
        "storage"
    ],

    "background": {
        "scripts": ["src/background.js"]
    }
}

这是我得到的: screenshot

但是,如果我将清单更改为:

"permissions": [
     "https://prod-relapi.ewp.gg/persisted/gw/*",
     "webRequest",
     "webRequestBlocking",
     "storage"
 ]

在 background.js 中:

browser.webRequest.onCompleted.addListener(
    saveData,
    {
        urls: ["https://prod-relapi.ewp.gg/persisted/gw/*"],
        types: ['xmlhttprequest']
    });

控制台中没有显示任何内容。我错过了什么,以便听众对特定的 url 模式感到兴奋?

标签: javascriptgoogle-chrome-extensionfirefox-addon-webextensions

解决方案


引用 MDN

To intercept resources loaded by a page (such as images, scripts, or stylesheets), the extension must have the host permission for the resource as well as for the main page requesting the resource. For example, if a page at "https://developer.mozilla.org" loads an image from "https://mdn.mozillademos.org", then an extension must have both host permissions if it is to intercept the image request.

Quoting Chrome API documentation:

Starting from Chrome 72, an extension will be able to intercept a request only if it has host permissions to both the requested URL and the request initiator.

So you need to add "https://watch.euw.lolesports.com/*" in manifest's "permissions".


推荐阅读