javascriptchromium

Unable to append javascript with document.body.appendChild


I'm trying to append javascript to a loaded page by:

var sc = document.createElement('script');
sc.content = "<script>alert('aa')</script>";
document.body.appendChild (sc);

But that didn't work in chromium:

enter image description here


Solution

  • You don't put <script>...</script> inside the content of a script element. But more to the point, I don't think they have a content property (I don't see one here, for instance).

    If I recall correctly, the most reliable way to put content within a script element at runtime is via createTextNode and appendChild, e.g.: Live example | source

    var sc = document.createElement('script');
    sc.appendChild(document.createTextNode("alert('aa')"));
    document.body.appendChild(sc);
    

    ...but I wouldn't be surprised to find that some older browsers required you to set innerText or something instead.