我试图拦截对特定URL的Web请求,并且在发送请求之前,通过Web扩展本地消息传递(这是异步) 。由于本地消息传递是异步的,所以在从本地消息传递响应获得cookie值之前,会发送Web请求。Web扩展拦截Web请求联系本地消息传递以设置请求Cookie的值
这是代码片段。如何使此流程同步,以便加载cookie,然后发送拦截的Web请求。
browser.webRequest.onBeforeRequest.addListener(
loadCookie,
{urls: ["https://some-url/*"]},
["blocking"]
);
function loadCookie(requestDetails)
{
console.log("Gettting Cookie Data for"+requestDetails.url);
var sending = browser.runtime.sendNativeMessage("native_app","getCookieData");
sending.then(onSuccess, onError);
}
function onSuccess(response)
{
console.log("Received: " + JSON.stringify(response));
setCookie(response);
}
function onError(error)
{
console.log("Error");
}
function setCookie(resp)
{
if(typeof resp != 'undefined'){
var now = new Date();
var time = Math.round(now.getTime()/1000);
var expireTime = time + 15*60;
browser.cookies.set({
url: "https://some-domain/*",
name: "req_cookie",
value: resp,
secure: true,
expirationDate: expireTime
});
}
console.log("Set a cookie");
}
我认为你唯一的机会就是当你想要拦截的URL是页面上的链接时 - 你可以在mouseover事件监听器中启动预取数据,以便在链接被点击前准备就绪。 – wOxxOm
我可以为超链接做到这一点,但我需要这样做的正常请求,通过用户在地址栏中输入网址发生。 –