繁体   English   中英

使用chrome.webRequest.onBeforeRequest进行同步XHR请求

[英]Making synchoronous XHR request with chrome.webRequest.onBeforeRequest

我正在寻找一个Chrome扩展程序,它与chrome.webRequest.onBeforeRequest挂钩,以确定是否阻止当前页面请求。 因此,我需要向API发出请求以确定它。

有没有一种方法可以使checkUrl请求同步以满足chrome.webRequest.onBeforeRequest的要求?

function checkUrl(url, callback) {
  let api    = 'http://localhost:9000/filter';
  let data   = {
    url: url,
  };

  let json = JSON.stringify(data);

  let xhr = new XMLHttpRequest();
  xhr.open('POST', api, true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.setRequestHeader('X-Bark-Email', email);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      callback(xhr.response);
    }
  }
  xhr.send(json);
}

function onBeforeRequestHandler(details) {
  let url = new URL(details.url);

  console.log(details.type, ": ", url.host)

  checkUrl(url, function(resp) {
    let status      = resp.status;
    let redirectUrl = resp.redirect_url;

    if (status == "allowed") {
      return { cancel: false }; // <<<<<  This doesn't work b/c of the callback
    } else {
      return { redirectUrl: redirectUrl };
    }
  });
}

chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestHandler,
  {
    urls: ["<all_urls>"],
    types: ["sub_frame", "main_frame", "xmlhttprequest"]
  },
  ["blocking"]
);

我交换了:

  xhr.open('POST', api, true);

对于

  xhr.open('POST', api, false);

这使得请求同步。 然后返回xhr请求的结果并使用该内联:

  return JSON.parse(xhr.response);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM