javascript - Chrome webRequest onBeforeRequest 在收到函数返回后不会重定向
问题描述
所以基本上我正在制作某种网络钓鱼网站检测器。
我的程序所做的是:
- 将 URL 发送到 localhost 中的 Flask 后端
- 等待后端处理 URL(我必须使 XHR 同步,否则它只会在收到结果之前重定向)
- 后端将结果(0 = 合法,1 = 钓鱼)发送回扩展程序
- 扩展根据结果重定向。如果为 0,则重定向回 URL。如果为 1,则重定向到本地页面
blocked.html
问题在于重定向。它只是重定向回 URL,无论结果如何。
代码:
manifest.json
{
"manifest_version": 2,
"name": "Phishing Site Detector",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"web_accessible_resources": [
"blocked.html"
],
"permissions": [
"webRequest",
"webRequestBlocking",
"<all_urls>"
]
}
背景.js
function checkurl(url){
console.log("checking URL..");
console.log(url);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if (xhr.readyState == 4) {
console.log("response received!");
console.log(xhr.responseText);
return xhr.responseText;
}
};
xhr.open("GET", "http://localhost:5000/"+url, false);
xhr.send();
};
chrome.webRequest.onBeforeRequest.addListener(
function(details){
var res = checkurl(details.url);
if(res == "0"){
console.log("redirecting back..");
return { redirectUrl: details.url };
}else if(res == "1"){
console.log("blocked!");
return { redirectUrl: "chrome-extension://njfcgcmoahjhhbggmapgphfapmedmjhj/blocked.html" };
}
},
{
urls: ["http://*/*", "https://*/*"],
types: ["main_frame"]
},
["blocking"]
);
提前致谢。
解决方案
onBeforeRequest 在 Chrome 扩展中不能是异步的,因此您的代码几乎就在那里,但是当使用已弃用的同步 XHR 时,它send
会等待响应,因此您只需立即访问响应而不是 xhr.onreadystatechange 事件:
function checkurl(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:5000/' + url, false); // synchronous
xhr.send();
return xhr.responseText;
}
推荐阅读
- assembly - 绕行功能崩溃
- python - 从 mayavi 场景中删除工具栏
- sql - ORA-02291 - “违反完整性约束 - 未找到父键” - 仅插入很少的错误
- html - 如何从视频链接中点击并让它在下面的区域播放?
- c# - C# 运算符“+”不能应用于“IntPtr”和“int”类型的操作数
- asp.net - Unity DI - C# 依赖注入如何与存储库类构造函数一起使用?它仅适用于控制器?
- python - 在 Python 中读取文本文件的重复数字
- java - 如何将在另一个类中获取的网络数据返回到 Android MainActivity?
- arrays - GoLang 字符串为空
- mysql - 如果两列与 MySQL 不匹配,则删除一行