Javascript Chrome webRequest onBeforeRequest获胜';在接收到函数返回后不重定向
因此,基本上我正在制作某种钓鱼网站检测器。Javascript Chrome webRequest onBeforeRequest获胜';在接收到函数返回后不重定向,javascript,google-chrome-extension,Javascript,Google Chrome Extension,因此,基本上我正在制作某种钓鱼网站检测器。 我的程序所做的是: 将URL发送到localhost中的Flask后端 等待后端处理URL(我必须使XHR同步,否则它将在收到结果之前重定向) 后端将结果(0=合法,1=钓鱼)发送回扩展 扩展将根据结果重定向。如果为0,则重定向回URL。如果为1,则重定向到本地页面blocked.html 问题在于重定向。它只是重定向回URL,不管结果如何 代码: manifest.json { "manifest_version": 2,
我的程序所做的是:
blocked.html
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>"
]
}
提前感谢。onBeforeRequest在chrome扩展中无法异步,因此您的代码几乎就在那里,但是当使用不推荐的同步XHR时,它的
send
会等待响应,因此您只需立即访问响应,而不是XHR.onreadystatechange事件:
函数检查url(url){
var xhr=new XMLHttpRequest();
xhr.open('GET','http://localhost:5000/“+url,false);//同步
xhr.send();
返回xhr.responseText;
}
onBeforeRequest在chrome扩展中不能异步,因此您的代码几乎就在那里,但是当使用不推荐使用的同步XHR时,它的发送
会等待响应,因此您只需立即访问响应,而不是XHR.onreadystatechange事件:
函数检查url(url){
var xhr=new XMLHttpRequest();
xhr.open('GET','http://localhost:5000/“+url,false);//同步
xhr.send();
返回xhr.responseText;
}
checkurl()函数实际上不返回任何内容;它只是记录结果。顺便说一句,使用async listener(如前所述,使用BlockingResponse返回承诺解析的那个)难道不可能吗?@raina77ow我还没有尝试过。但目前,接受的答案还可以,checkurl()函数实际上不返回任何内容;它只是记录结果。顺便说一句,使用async listener(如前所述,使用BlockingResponse返回承诺解析的那个)难道不可能吗?@raina77ow我还没有尝试过。但目前,公认的答案还不错。
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"]
);