• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 122
  • Last Modified:

Injecting Javascript Not Working

Because of the way we are loading these pages, we want to use the DOM to inject <SCRIPT> variables and source...

function putJS(cid, pid) {
    var _line1 = '<scr' + 'ipt>var zflag_nid="607"; var zflag_cid="' + cid + '"; var zflag_sid="' + pid + '"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="94";<\/script>';
    var _line2 = "<scr" + "ipt src='http://newt1.com/jsc/z5/fo.js'><\/script>";
    var _script = document.createElement("div");
    _script.innerHTML = _line1 + _line2;
    (document.getElementsByTagName("body")[0] || document.documentElement).appendChild(_script);

Open in new window

But, for some reason - its not working.

I've also tried:

function putJS(cid, pid) {
   var _script = document.createElement("script");
    _script.innerHTML = 'var zflag_nid="607"; var zflag_cid="' + cid + '"; var zflag_sid="' + pid + '"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="94";';
    //_script.onload = scriptLoaded;
    var _scriptSource = document.createElement("script");
    _scriptSource.src = "http://www.com/fo.js";
    _script.async = true;
    _scriptSource.async = true;
    var docFrag = document.createDocumentFragment();
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(docFrag);

Open in new window

And I get an error about writing to the page...  

I'm not sure if there is anything I can do... I have no access to the fo.js script also, as its being loaded externally from a source we do not own.

1 Solution
Alexandre SimõesManager / Technology SpecialistCommented:
Here's a small example: http://jsfiddle.net/AlexCode/4RFg7/
function injectScript(arg1){
    var funct = "function main() { alert('injected: " + arg1 + "'); }";
    var scriptElem = document.createElement('script');
    scriptElem.appendChild(document.createTextNode('('+ funct +')();'));
    (document.body || document.head || document.documentElement).appendChild(scriptElem);

injectScript('parameter 1');

Open in new window

var sr = document.createElement("script")
sr.type = "text/javascript";
sr.src = "http://www.com/fo.js";

Open in new window

your -
will fail, , as the  document.createElement("script")   has NO  "innerHTML"

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now