# 内容安全策略：页面设置阻止了内联脚本资源的加载

- **ID:** `flutter/flutter-web-csp-violation`
- **领域:** flutter
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

Flutter Web 应用需要内联脚本（例如用于 CanvasKit 或 Service Worker），但服务器的内容安全策略（CSP）标头阻止了它们，通常是由于缺少 'unsafe-inline' 或 nonce。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.16 | active | — | — |
| Dart 3.2 | active | — | — |
| Chrome 120 | active | — | — |
| Firefox 121 | active | — | — |

## 解决方案

1. ```
   Update the server's CSP header to include 'script-src 'self' 'unsafe-inline' 'unsafe-eval';' for Flutter web apps. For nginx: `add_header Content-Security-Policy "script-src 'self' 'unsafe-inline' 'unsafe-eval'";`
   ```
2. ```
   Use a nonce-based CSP: generate a random nonce per request and add it to the script tag in the HTML template, then set `script-src 'self' 'nonce-{nonce}'`.
   ```
3. ```
   Build Flutter web with `--web-renderer canvaskit --csp` to enable CSP-compatible mode, then adjust the server CSP to allow only 'self' for scripts and styles.
   ```

## 无效尝试

- **** — Disabling CSP exposes the app to XSS attacks and violates security best practices; many hosting providers enforce CSP at the infrastructure level. (60% 失败率)
- **** — Switching renderers may change visual behavior and performance; it also doesn't resolve CSP issues if the app still uses inline scripts for other purposes. (50% 失败率)
- **** — If the server already sends a CSP header, the meta tag is ignored; the more restrictive policy applies, so the error persists. (70% 失败率)
