在内容脚本上调试“JSON 输入错误的意外结束”

Debug `Unexpected end of JSON input Error` on content script

我遇到了一个非常奇怪的错误,我的获取功能在我的内容脚本上不起作用,但在我的弹出页面上起作用。

我收到的错误是 Uncaught (in promise) SyntaxError: Unexpected end of JSON input

我也尝试过禁用其他扩展程序的隐身模式,但没有任何效果。

但是,它完全可以在我的 Brave 浏览器上运行。

const getRequest = function (url) {
  return window.fetch(url, {
    method: 'GET'
  }).then(res => res.json());
}

Chrome 网络扩展(内容脚本)中不再允许跨源提取 (CORS)。请求将通过,但响应主体将始终为空,这就是为什么在尝试解析 JSON.

时出现错误的原因

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.

参见:Changes to Cross-Origin Requests in Chrome Extension 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:

旧内容脚本,进行跨域获取:

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 => ...)

新的内容脚本,改为要求其后台页面获取数据:

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

新扩展后台页面,从已知URL获取并中继数据:

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