3

How can I execute a script in the innerHtml of an HTML element. I have a string of HTML with a script element included, like the HTML sample below.

<strong>asdasd</strong><br>
<p>asdasd</p>
<script>alert('aa')</script>

I have tried to inject this HTML into my component, with the following HTML code in my component's template.

<div [innerHTML]="customScript"></div>

My problem is that the script in the HTML string does not run. How can I make the contents of the script element embedded in the innerHTML of the div element execute?

In the second code snippet, the customScript variable isn't hard-coded anywhere. It is a string that comes from the back-end. It can contain any tag like html, body, div, script (Yes! Script needs to be allowed!). I need to make any script in the customScript HTML string run in my component as normal html/script code.

6
  • @FernandoValderramaGuayán Since this is angular, where the creation/modification/deletion of components can easily be dynamic, the change could easily not be associated with a page load. Commented Dec 4, 2020 at 23:32
  • You need to pass it through the sanitizer Commented Dec 4, 2020 at 23:32
  • Where is that customScript html coming from? It's generally not a good practice to do what you are trying to do. You would want to do that in a more "native" Angular way. If that customScript is hardcoded, you could just call the alert in a lifecycle method. Commented Dec 4, 2020 at 23:37
  • @ulmas customScript isn't hardcoded anywhere. It's just a string that comes from back-end. It can contains any tag like html, body, div, script (yes! script needs to be there) and need to make this string running in my component as normal html/script code. Commented Dec 4, 2020 at 23:52
  • Short answer: don't. You're using angular: trigger JS that injects a <script> into document.head. Also, never use alert. We've had the console API since 2010, use it. Commented Dec 4, 2020 at 23:57

1 Answer 1

-1

You can use a regex to get all contents of <script/>, then use eval() to run it.

Sign up to request clarification or add additional context in comments.

1 Comment

What do you mean by ElementRef? How did you solve it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.