如何收听XMLHttpRequests-浏览器扩展

时间:2019-10-13 13:36:14

标签: javascript google-chrome-extension firefox-addon firefox-webextensions

我的脚本

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://get.example.com/dashboard/summary网页向“ https://example.com/dashboard”发出了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。当我检查背景页面时,只能看到消息01。看不到消息02或消息03。

输出:background.js

Msg 01 - Background script is running.

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

1 个答案:

答案 0 :(得分:1)

这一切都取决于实际情况。这是您可以处理的一些想法。

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

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

您可以

  • 在内容脚本中具有XHR并使用 webRequest 后台脚本中的API可以监听HTTP请求
  • 使用runtime.sendMessage()从内容脚本转换为后台脚本,以在后台脚本中运行XHR

然后从后台脚本

相关问题