【问题标题】:Chrome extension with Angular: CSP inline-policy error. Refused to execute inline event handler带有 Angular 的 Chrome 扩展:CSP 内联策略错误。拒绝执行内联事件处理程序
【发布时间】:2021-07-26 17:43:56
【问题描述】:

我想将注销功能关联到 chrome 扩展的导航栏。 但是当我单击相应的选项卡时,它不会导航到登录组件并给我以下错误:

拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“script-src 'self' 'unsafe-eval'”。启用内联执行需要“unsafe-inline”关键字、哈希(“sha256-...”)或随机数(“nonce-...”)。

https://developer.chrome.com/docs/apps/contentSecurityPolicy/ 表示我们不能在您的 Chrome 应用页面中使用内联脚本,并且限制禁止块和事件处理程序 ()。

我在 stackoverflow 上看到过解决方案,例如 Refused to execute inline event handler because it violates CSP. (SANDBOX),它说我们可以向按钮添加一个 id,然后在 javascript 上添加一个事件监听器,但是这样我就无法添加这行代码:this.router .navigate(['/signin']) 原样。

我认为我可以将 typescript 文件转译为 javascript,但如果我将 document.getElementById() 放在 ts 文件上,它会检索到 null,我认为 typescript 是在模板之前加载的。

如何使用 Angular 和 Typescript 解决这个 chrome 扩展错误?

我的代码如下:

App.component.html

    <mat-tab>
      <ng-template mat-tab-label>
          <button mat-button [matMenuTriggerFor]="menuAccount"><mat-icon fontSet="fas" style="font-size: 18px;" fontIcon="fa-user-circle"></mat-icon></button>
      </ng-template>
      <mat-menu #menuAccount="matMenu">
        <button mat-menu-item><mat-icon fontSet="fa" style="font-size: 16px;" fontIcon="fa-cogs"></mat-icon><span>{{dpd_items[0].viewValue}}</span></button>
        <button (click)="logout()" mat-menu-item><mat-icon fontSet="fas" style="font-size: 16px;" fontIcon="fa-sign-out-alt"></mat-icon><span>{{dpd_items[1].viewValue}}</span></button>
      </mat-menu>
    </mat-tab>

App.component.ts

logout() {
  this.router.navigate(['/signin']);
}

【问题讨论】:

    标签: angular typescript google-chrome-extension content-security-policy


    【解决方案1】:

    对我来说,这个错误来自被提取到 InlineJs 的 CSS,而不是来自 Angular 代码本身。

    这对我来说意味着它可以与构建手表一起使用,

    "angular:watch": "ng build --watch",
    

    但不是构建产品。

    "angular:build": "ng build --configuration=production",
    

    这里的解决方案是禁用 extractCSS。

    您可以在生产中调整 angular.json 为 extractCss: false

    {
        ...
        "projects": {
            "project-name": {
                ...
                "architect": {
                    "build": {
                        ...
                        "configurations": {
                            "production": {
                                ...
                                "extractCss": false,
                                ...
    

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2020-09-26
      • 2022-01-18
      • 2018-12-03
      • 2021-12-10
      • 2016-07-19
      • 2020-02-12
      • 2014-10-26
      • 2021-08-06
      相关资源
      最近更新 更多