在内容脚本上调试`JSON输入错误`的意外结束 [英] Debug `Unexpected end of JSON input Error` on content script

查看:104
本文介绍了在内容脚本上调试`JSON输入错误`的意外结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个非常奇怪的错误,我的fetch函数无法在我的内容脚本上运行,但可以在我的弹出页面中运行。

I am having this very strange bug where my fetch function won't work on my content script but works from my popup page.

我得到的错误是未捕获(在承诺中)SyntaxError:JSON输入的意外结束

我还尝试了隐身模式并禁用了其他扩展程序但是没有做任何事情。

I also tried Incognito mode with other extensions disabled but that didn't do anything.

然而,它完全适用于我的Brave浏览器。

However, it's fully working on my Brave browser.

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


推荐答案

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

Cross-origin fetches (CORS) is no longer allowed in Chrome Web Extensions (content scripts). The request will go through, but the response body will always be empty, which is why you are getting an error when trying to parse to JSON.


为了提高安全性,Chrome扩展程序中的
内容脚本很快就会禁止跨源提取。这些请求可以从
扩展背景页面转发,并在需要时转发到内容脚本

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.

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


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

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:

旧内容脚本,进行跨源提取:<​​/ p>

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

新的扩展背景页面,从已知URL获取并转发数据:

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

这篇关于在内容脚本上调试`JSON输入错误`的意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆