javascript - 如何监听 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.
我做错了什么,我该如何解决?
解决方案
这一切都取决于实际情况。这里有一些你可以研究的想法。
最好使用标准 JavaScript XMLHttpRequest而不是使用XMLHttpRequest.prototype
.
内容脚本和浏览器具有不同的范围,并且出于安全考虑不直接交互。
你可以
- 在内容脚本中有 XHR 并在后台脚本中使用 webRequest API 来监听 HTTP 请求
- 使用从内容脚本到后台脚本的runtime.sendMessage()在后台脚本中运行 XHR
然后从后台脚本
- 使用 tabs.sendMessage()向 contentscript 发送消息
- 使用tabs.executeScript()直接在内容范围内运行脚本或在内容脚本中启动函数
推荐阅读
- azure - 是否可以使用 azure powershell 在 azure 中查看日志警报?
- linux - 复制路径中的文本(Bash)
- tsql - 需要按数量值为临时表分配值
- sql - 如何在 CASE When 语句中检查 varchar 变量是否为数字
- c# - 针对不同类型实体的可扩展审批工作流程的系统设计
- c# - 在 Visual Studio 2017 中设置默认 C# 构建语言版本
- shiny - 是否可以在降价文档中仅嵌入闪亮的应用程序输出?
- python - 避免多个 IF 以确保 McCabe 复杂性
- python - django:如果我们使用自定义模板,如何在内联模型中找到上下文变量
- javascript - React native - AsyncStorage, wait and sync