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

Tox*_*nyc 2 javascript fetch google-chrome-extension

我有一个非常奇怪的错误,我的 fetch 函数不能在我的内容脚本上工作,但可以在我的弹出页面上工作。

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

我还尝试了禁用其他扩展的隐身模式,但这没有做任何事情。

但是,它完全适用于我的 Brave 浏览器。

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

Mic*_*kel 5

Chrome Web 扩展程序(内容脚本)中不再允许跨源提取 (CORS)。请求将通过,但响应正文将始终为空,这就是您在尝试解析为 JSON 时收到错误的原因。

为了提高安全性,Chrome 扩展程序中的内容脚本很快将禁止跨源提取。此类请求可以从扩展后台页面发出,并在需要时中继到内容脚本。

请参阅:Chrome 扩展内容脚本中跨源请求的更改

当需要跨源提取时,从扩展后台页面而不是在内容脚本中执行它们。根据需要将响应中继到内容脚本(例如,使用扩展消息传递 API)。例如:

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

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 => ...)
Run Code Online (Sandbox Code Playgroud)

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

chrome.runtime.sendMessage(
    {contentScriptQuery: "queryPrice", itemId: 12345},
    price => ...);
Run Code Online (Sandbox Code Playgroud)

新的扩展后台页面,从已知 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.
    }
  });
Run Code Online (Sandbox Code Playgroud)