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

Angular中如何去除unsafe标记,使tg协议链接变为安全链接

解决Angular中tg://链接被标记为unsafe的问题

Angular默认会把非HTTP/HTTPS这类标准协议的链接标记为unsafe,tg://属于自定义协议,所以会被拦截。解决方法是通过DomSanitizer将其标记为安全链接,下面两种方案任选其一:

方案一:在组件内直接处理链接

  1. 在组件中注入DomSanitizer
  2. 写一个方法生成安全的telegram链接
  3. 模板中调用该方法绑定href

组件代码示例:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements OnInit {
  adsX: any[] = []; // 你的广告数据

  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit(): void {
    // 初始化adsX数据
  }

  getSafeTelegramUrl(username: string): SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(`tg://resolve?domain=${username}`);
  }
}

修改后的模板代码:

<ul>
  <li *ngFor="let ads of adsX">
    <ng-container *ngIf="ads.telegram">
      <a [href]="getSafeTelegramUrl(ads.telegram)"> {{ ads.telegram }} </a>
    </ng-container>
  </li>
</ul>

方案二:自定义管道(复用性更强)

如果多个组件都需要处理这类链接,推荐写一个通用管道:

  1. 创建safe.pipe.ts文件:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(url: string): SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
}
  1. 在对应的NgModule中声明并导出该管道:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SafePipe } from './safe.pipe';

@NgModule({
  declarations: [SafePipe],
  exports: [SafePipe],
  imports: [CommonModule]
})
export class SharedModule { }
  1. 模板中使用管道:
<ul>
  <li *ngFor="let ads of adsX">
    <ng-container *ngIf="ads.telegram">
      <a [href]="'tg://resolve?domain=' + ads.telegram | safe"> {{ ads.telegram }} </a>
    </ng-container>
  </li>
</ul>

⚠️ 注意:只对可信来源的链接使用上述方法,避免引入XSS安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:47:19