Open BillCarsonFr opened 4 years ago
Avoid Cross-Origin Fetches in Content Scripts When cross-origin fetches are needed, perform them from the extension background page rather than in the content script. Relay the response to the content scripts as needed (e.g., using extension messaging APIs). For example:
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.
}
});
Due to -> Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/json. See for more details.
https://www.chromium.org/Home/chromium-security/extension-content-script-fetches