How to stop CORB from blocking requests to data resources that respond with CORS headers?

前端 未结 3 1822
广开言路
广开言路 2020-11-27 06:57

I am developing a Chrome extension which makes requests from certain websites to an API I control. Until Chrome 73, the extension worked correctly. After upgrading to Chrome

3条回答
  •  爱一瞬间的悲伤
    2020-11-27 07:02

    See https://www.chromium.org/Home/chromium-security/extension-content-script-fetches

    To improve security, cross-origin fetches will soon be disallowed from content scripts in Chrome Extensions. Such requests can be made from extension background pages instead, and relayed to content scripts when needed.

    You can do that to avoid Cross-Origin.

    Old content script, making a cross-origin fetch:

    var itemId = 12345;
    var url = "https://another-site.com/price-query?itemId=" +
             encodeURIComponent(request.itemId);
    fetch(url)
      .then(response => response.text())
      .then(text => parsePrice(text))
      .then(price => ...)
      .catch(error => ...)
    

    New content script, asking its background page to fetch the data instead:

    chrome.runtime.sendMessage(
        {contentScriptQuery: "queryPrice", itemId: 12345},
        price => ...);
    

    New extension background page, fetching from a known URL and relaying data:

    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.contentScriptQuery == "queryPrice") {
          var url = "https://another-site.com/price-query?itemId=" +
                  encodeURIComponent(request.itemId);
          fetch(url)
              .then(response => response.text())
              .then(text => parsePrice(text))
              .then(price => sendResponse(price))
              .catch(error => ...)
          return true;  // Will respond asynchronously.
        }
      });
    

提交回复
热议问题