0

I am trying to insert Javascript code into HTML via Javascript.

Inserting this code into HTML does not work, the code is not executed :

<script>

function callAlert(){
alert('test');
}

</script>

This code is executed :

<img src="xxx" onerror="alert('test')">

This does not call the function so the alert is not executed :

<img src="xxx" onerror="callAlert();">

Why onerror alert is executed and onerror calling function not?

Tadeas J
  • 19
  • 2

2 Answers2

0

You can no longer insert a <script> tag using el.innerHTML. This is a security issue that has been added fairly recently.

Go to this page: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

and scroll down to the Security considerations section.

It mentions that you can not add a <script> tag but it is not fool proof. Things like you describe can still cause script to run:

const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert

If you really need to add new JavaScript from existing JavaScript you will need to do something like the following:

var s = document.createElement('script');
s.textContent = 'function callAlert(){alert(\'test\');}';
document.head.appendChild(s);
callAlert();
Intervalia
  • 10,248
  • 2
  • 30
  • 60
-1

Try putting the script into the head of the page, it could be that the function is executed before it's defiend.

If this isn't working please tell what error your console returns.

Matthew
  • 1
  • 5