Access-Control-Allow-Origin on chrome extension

后端 未结 4 1849
我在风中等你
我在风中等你 2020-12-28 19:36

I\'m making a Chrome extension which pulls data from my own server. It uses about 4 httpRequests at a time, but sometimes I get console error as follows:

XMLHt

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 20:09

    You will need to set up permissions in manifest.json:

      "permissions": [
        "https://example.com/" // if you need a particular site
        ""           // if you need any site (this will incur 
                               // manual review process in Chrome web store, mind you)
      ],
    

    Please note, that since Chrome 85 extn content scripts are subject to the same CORS policy as vanilla web requests. Which means that the only way to do cross-site requests in extn now is to fetch in background script and pass the result to content script:

    // 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.
        }
      });
    

提交回复
热议问题