使用chrome.webRequest.onBeforeRequest发出同步XHR请求

时间:2019-04-15 21:10:14

标签: javascript google-chrome google-chrome-extension

我正在寻找一个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"]
);

1 个答案:

答案 0 :(得分:0)

我换了:

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

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

,使请求同步。然后从xhr请求返回结果并使用该内联:

  return JSON.parse(xhr.response);