Hello! Why does this code not work?

alert("So, what this does is bacsically just injects some code in the first script tag.");
function InjectCode(){
    window.onload = function(){
    var a = document.getElementsByTagName("script");
    var b = a.length;
    var c = a[1];
    var d = c.innerHTML;
    var e = "function runInjectedCode(){c = 'IT WORKS!!!';}";
    var f = d+e;
    c.innerHTML = f;

Please help. When I add a alert that delays by three, defines the variable c, and executes the function runInjectedCode(), but it tells me that it is not a function.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


Holy cow those variable names are obtuse.

You are overwriting the c variable inside the runInjectedCode function body.

// c is now the string 'IT WORKS!!!'
var e = "function runInjectedCode(){c = 'IT WORKS!!!';}";

// There is no innerHTML method on the string
c.innerHTML = f;

It is like if you did this:

var str = 'IT WORKS!!!'
// undefined

Try logging to the console in the function or doing an alert instead.

A suggestion, please use suggestive variable names even if they are long to type. You will improve your readability of code and make it easier for debugging

1 Like