Here is a scenario:
- you have some software/component that inserts partial HTML into page using JavaScript element.innerHTML function;
- you can insert any HTML tags including <script>;
- 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:
- Smuggle arbitrary JavaScript into the existing document (http://24ways.org).
- Can scripts be inserted with innerHTML? (Stackoverflow)
smart one , thanks 4 sharing
Check out this one, i think it is better than the workaround above: http://xahlee.info/js/js_insert_js_code.html