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

谷歌扩展调用Google Calendar API遇CSP内联脚本执行错误求解决方案

解决Chrome扩展中Google Calendar API的CSP内联脚本错误

问题描述

我正在开发一款Chrome扩展,参考Google Calendar API的JavaScript快速入门教程尝试获取日历事件,但运行扩展时控制台返回以下错误:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src-elem script-src 'self' https://apis.google.com https://accounts.google.com/gsi/client". Either the 'unsafe-inline' keyword, a hash ('sha256-pI/ySU4r4cVLaARgTBReFoMKXEWbRpEV8/bixrOT+MM='), or a nonce ('nonce-...') is required to enable inline execution.

我的manifest.json配置如下:

{
  "name": "Custom Newtab",
  "description": "Personalized override of Chrome New Tab page.",
  "version": "1.0",
  "manifest_version": 2,
  "chrome_url_overrides": { "newtab": "bruh.html" },
  "oauth2": {
    "client_id": "__clientID__",
    "scopes": [
      "profile email",
      "https://www.googleapis.com/auth/contacts",
      "https://www.googleapis.com/auth/calendar",
      "https://www.googleapis.com/auth/calendar.readonly"
    ]
  },
  "content_security_policy": "script-src-elem script-src 'self' https://apis.google.com https://accounts.google.com/gsi/client; object-src 'self'",
  "permissions":  [
    "identity",
    "identity.email"
  ]
}

bruh.html完全沿用教程Step 1的示例代码,请问该如何解决这个问题?


问题根源

官方示例的HTML包含内联脚本(直接写在<script>标签里的代码,未引用外部文件),而Chrome扩展的CSP(内容安全策略)默认禁止内联脚本,你的manifest配置也未添加允许这类脚本的规则,因此触发了错误。

解决步骤

1. 迁移内联脚本到外部JS文件

把bruh.html里所有内联的<script>...</script>代码全部提取出来,保存为独立的JS文件,比如命名为app.js。

2. 修改HTML引用外部脚本

在bruh.html中替换原内联脚本,改为引用外部文件:

<script src="app.js"></script>

3. 可选:保留内联脚本的CSP配置调整

如果必须保留少量内联脚本,可以把错误提示里给出的哈希值添加到CSP规则中:

"content_security_policy": "script-src-elem script-src 'self' https://apis.google.com https://accounts.google.com/gsi/client 'sha256-pI/ySU4r4cVLaARgTBReFoMKXEWbRpEV8/bixrOT+MM='; object-src 'self'"

但更推荐完全移除内联脚本,符合扩展的安全规范。

4. 版本兼容提示

你的扩展使用的是Manifest V2,Chrome对V2的支持正在逐步终止,建议考虑迁移到Manifest V3。V3的CSP配置格式略有不同,且不允许unsafe-inline(除非配合nonce),迁移后同样需要避免内联脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:09:22