You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Chrome扩展加载Google Charts遇CSP报错求助

解决Chrome扩展加载Google Charts的CSP报错问题

问题原因

Chrome扩展Manifest V3默认内容安全策略(CSP)仅允许加载本地('self')脚本,你直接在HTML中引入了外部Google Charts脚本,同时内联脚本也不符合默认CSP规则,导致加载被拦截。

解决方案

1. 修改manifest.json的CSP配置

在manifest.json中添加content_security_policy字段,允许加载Google Charts相关外部脚本:

{
  "name": "name",
  "description": "description",
  "icons": {
    "16": "icon.png",
    "32": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  },
  "action": {
      "default_popup": "index.html"
  },
  "background": {
      "service_worker": "./scripts/background.js",
      "type": "module"
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self' https://www.gstatic.com; object-src 'self'"
  },
  "manifest_version": 3,
  "version": "1.0.1"
}
  • extension_pages指定扩展页面(如popup)的CSP规则
  • script-src添加https://www.gstatic.com,允许加载Google Charts的loader.js
  • 若后续加载其他Google Charts资源报错,可补充https://www.googleapis.com到script-src中

2. 移除HTML内联脚本(推荐)

Manifest V3严格限制内联脚本,规范做法是将内联代码移到单独本地JS文件:
创建chart.js文件,内容如下:

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses'],
    ['2004',  1000,      400],
    ['2005',  1170,      460],
    ['2006',  660,       1120],
    ['2007',  1030,      540]
  ]);

  var options = {
    title: 'Company Performance',
    curveType: 'function',
    legend: { position: 'bottom' }
  };

  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

  chart.draw(data, options);
}

修改index.html,引入本地脚本:

<html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript" src="chart.js"></script>
</head>
<body>
  <div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

3. 重新加载扩展

修改文件后,打开Chrome扩展管理页面,点击扩展的「重新加载」按钮,确保新配置生效。

内容的提问来源于stack exchange,提问作者LSG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 02:17:40