How to execute JavaScript after inserting into element.innerHTML automatically

Here is a scenario:

  1. you have some software/component that inserts partial HTML into page using JavaScript element.innerHTML function;
  2. you can insert any HTML tags including <script>;
  3. you can not call any JS function (software/component does not have such functionality), and inserted script using innerHTML is not executed automatically.

After some lost time trying to come up with the solution, I found the following trick using image tag and onload attribute. Again if you try to use script tag, it will not work:
<script type="text/javascript">alert('testing')</script>
However code with image trick will execute JavaScript automatically:
<img src="/images/1x1-transparent.png" onload="alert('testing');this.parentNode.removeChild(this);" />

Note that removeChild, will remove just inserted image, so your HTML code stays unaffected.

Sources:

2 replies on “How to execute JavaScript after inserting into element.innerHTML automatically”

Comments are closed.