Trusted Types Polyfill Angular

172 views Asked by At

I want to use the trusted type polyfill from w3c in my angular project. The problem is I can't make it working. Using the Trusted Types API in supporting browsers works fine, but when I use the polyfill it does not work.

I installed the polyfill with

npm install trusted-types

Then I imported the package in a service by using

import { trustedTypes as trustedTypesPolyfill } from 'node_modules/trusted-types'

after that I created a policy by calling the createPolicy method:

this.domPurify = trustedTypesPolyfill
      .createPolicy('dom-purify', {
        createHTML: (input) => DOMPurify
          .sanitize(input,
            {
              USE_PROFILES: { html: true },
              RETURN_TRUSTED_TYPE: true
            }),
      });

For testing (I know this is not secure) I use the following methods to assign the values to the innerHTML properties:

  writeToInnerHtml() {
    this.renderer.setProperty(this.elementWithTT.nativeElement, 'innerHTML', this.trustedTypesService.domPurify.createHTML(this.value))
    this.renderer.setProperty(this.elementWithoutTT.nativeElement, 'innerHTML', this.value)
  }

Using the normal Trusted Type API in supporting browsers like Edge or Chrome works fine.

But the trusted type enforcement does not apply in e.g. Firefox (Thats the reason why I use the polyfill) and the values checked by createHTML just return an empty TrustedHTML object.

I appreciate any help. Thank you! :)

1

There are 1 answers

0
Emalsha Rasad On

You need to import the polyfill to the angular polyfills.ts file as well. At the end of the file add

import 'trusted-types';

I guess it will solve your problem.