inject js to head (with full-code in script)

14,299

Solution 1

Just tried this and it seemed to work. Try

function addJS(jsCode) {
    var s = document.createElement('script');

    s.type = 'text/javascript';
    s.innerText = jsCode;
    document.getElementsByTagName('head')[0].appendChild(s);
}

Demo here

Solution 2

Using jquery

   var head = document.getElementsByTagName('head')[0],
        script = document.createElement('script');

    $(script).attr('type' , 'text/javascript');    
    head.appendChild(script);
    $(script).append("alert('Hello')");
Share:
14,299
mmmh
Author by

mmmh

Updated on June 11, 2022

Comments

  • mmmh
    mmmh almost 2 years

    I want to add a script to the head of a site so the the head of the target html looks like so <head><script type="text/javascript">*some code...*</script></head>.


    With this script works that perfect:

    var head = document.getElementsByTagName('head')[0],
        script = document.createElement('script');
    
    script.src = 'http://www.example.com/example.js';    
    head.appendChild(script);
    

    But i don't want to use any link in source.

    So i'm tried to add some code like this:

        function addJS(jsCode) {
        var styleElement = document.createElement('script');
    
        styleElement.type = 'text/javascript';
    
           (scriptElement.javascript) {
            scriptElement.javascript.jsText = jsCode
            scriptElement.appendChild(document.createTextNode(jsCode))
    
        document.getElementsByTagName('head')[0].appendChild(scriptElement);
    }
    
    var jsCode = '';
    jsCode += 'code';
    jsCode += 'some more code';
    

    But I've failed. That script is not working.

    How can I add a Element to the head of any html site like this? Would be great if someone could help me.