Custom trusted types in Angular project

247 views Asked by At

I have a spot in my Angular application where I do not want the Angular sanitizer to sanitize my content. My goal is to create a custom trusted type policy in my angular project. But I could not figure out what is the best practice to create one, store them and use them in code later.

I know it works by using (window as any) And doing I was doing it in a separate trusted-types-service:

export class TrustedTypesService {
  readonly fooPolicy: any;

  constructor() {
    this.fooPolicy = (window as any).trustedTypes.createPolicy('foo', (bar) => {
      // ideally some sanitizing by e.g. DOM Purify
      return bar;
    });
  }
}

But is this the right and best way to do it?

I'd appreciate any help. Thank you :)

1

There are 1 answers

0
Schnikles On BEST ANSWER

The best way I found out to do it is the following:

export class TrustedTypesService {
  public readonly domPurify: TrustedTypePolicy;

  constructor() {
    // If browser does not support TTs => Tinyfill
    if (window.trustedTypes == undefined) {
      (window as any).trustedTypes = {
          createPolicy: (_name: string, rules: TrustedTypePolicyOptions) => rules
      };
    }

    // Creating the policy
    this.domPurify = window.trustedTypes.createPolicy('dom-purify', {
      createHTML: (input) => DOMPurify.sanitize(input,
        {
          USE_PROFILES: { html: true },
          RETURN_TRUSTED_TYPE: true
        }),
      createScript: (input) => *handle script sanitization*,
      ...
    });
  }
}