6

I am importing an HTML snippet from a third party and embedding it into some placeholder outside my Angular 7 application. There's one link starting with javascript: inside the snippet that will be prefixed with unsafe: by Angular which breaks its functionality.

The DOMSanitizer of Angular only seems to provide a way to bypass security for HTML strings. However, in below method I'm just reading the DOM node and appending it to a different destination. So I'd need to have a solution for a DOM node.

According to my research, the inserted nodes are OK directly after the appendChild call, but a few ms after that Angular adds the unsafe:.

How can I bypass security for DOM nodes?

 private insertPart(componentImportLinkId: string, targetSelector: string): void {
    try {
      const linkElement: any = document.getElementById(componentImportLinkId);
      const componentContent = linkElement.import;
      const componentTemplate = componentContent.querySelector('template');
      const importedComponentTemplateClone = document.importNode(componentTemplate.content, true);
      const appendToElement = document.querySelector(targetSelector);
      appendToElement.appendChild(importedComponentTemplateClone);
    } catch (e) {
      console.error(`PortalLayoutComponent.insertPart: Can not insert '${targetSelector}'`, e);
    }
  }
dude
  • 5,678
  • 11
  • 54
  • 81
  • Just a random guess, the DOMSanitizer link you provided also links to [`bypassSecurityTrustScript()`](https://angular.io/api/platform-browser/DomSanitizer#bypasssecuritytrustscript), did you try that? That said, regardless if this works or not, you must be 200% sure that the data you're importing from this 3rd party is "safe". – HamZa Dec 18 '18 at 09:30
  • 1
    @HamZa The `bypassSecurityTrustScript` also expects a string as parameter value, but what I have is only a DOM node. I'm 200% sure that the HTML is "safe", it's directly coming from a portal of the customer :-) – dude Dec 18 '18 at 18:52
  • 2
    According to [MDN](https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports), HTML Imports are obsolete. The article you linked to suggesting to use them is from 2013 (5 years old as of this writing). If you cannot convert to a standard HTML tag, then probably you should use an iframe and `bypassSecurityTrustResourceUrl`. Read the Angular docs about [trusting safe values](https://angular.io/guide/security#bypass-security-apis). – Old Pro Dec 21 '18 at 07:25
  • Can you please provide a stackblitz demo of what exactly you're trying to accomplish – Black Mamba Dec 27 '18 at 04:30

1 Answers1

0

You could get a String value of your DOM-Node by calling outerHTML() on componentTemplate

Daniel
  • 1