首页 > 解决方案 > 如何监听 XMLHttpRequests - 浏览器扩展

问题描述

我的脚本

var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    this.addEventListener('load', function() {
        //console.log(this.responseURL);        
        if(this.responseURL == "https://get.example.com/dashboard/summary")
        {
            // Run the function
            funMain();
        }
    });
    origOpen.apply(this, arguments);
};

function funMain() {
    // My codes
}

这是我的脚本,它按预期工作。它的作用是,它监听 XMLHttpRequests,当一个 XMLHttpRequest 被发送到“ https://get.example.com/dashboard/summary ”时,它调用funMain函数。由于这是一个事件,因此这不是一次性事件。这可以发生多次。此 XMLHttpRequest 由https://example.com/dashboard网页制作。

流程:如果通过https://example.com/dashboard网页向“ https://get.example.com/dashboard/summary ”发出 XMLHttpRequest,则调用函数。funMain

所以现在,我想使用这个工作脚本构建一个扩展。
这是我到目前为止所尝试的......

内容脚本

function funMain() {
    // My codes
}

注意:我知道我必须使用 browser.runtime.sendMessage() 在后台脚本和内容脚本之间进行通信。但目前,我正试图让事件函数(在后台脚本中)工作。

背景脚本

console.log("Msg 01 - Background script is running.");
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    this.addEventListener('load', function() {
        console.log("Msg 02 - " + this.responseURL);        
        if(this.responseURL == "https://get.example.com/dashboard/summary")
        {
            // Run the function
            // funMain();
            console.log("Msg 03 - Hello! I am working as expected.");
        }
    });
    origOpen.apply(this, arguments);
};

显现

{
  "manifest_version": 2,
  "name": "Beastify",
  "version": "1.0",

  "description": "des",
  "icons": {
    "48": "icons/beasts-48.png"
  },

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

  "content_scripts": [{
        "matches": [
            "*://*.example.com/dashboard"
        ],
        "js": [
            "content-script.js"
        ]
    }],

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

问题是,该事件没有按预期工作。因此,不能调用 funMain。当我检查背景页面时,我只能看到 Msg 01。我看不到 Msg 02 或 Msg 03。

输出:背景.js

Msg 01 - Background script is running.

我做错了什么,我该如何解决?

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

解决方案


这一切都取决于实际情况。这里有一些你可以研究的想法。

最好使用标准 JavaScript XMLHttpRequest而不是使用XMLHttpRequest.prototype.

内容脚本和浏览器具有不同的范围,并且出于安全考虑不直接交互。

你可以

  • 在内容脚本中有 XHR 并在后台脚本中使用 webRequest API 来监听 HTTP 请求
  • 使用从内容脚本到后台脚本的runtime.sendMessage()在后台脚本中运行 XHR

然后从后台脚本


推荐阅读