Search code examples
javascriptgoogle-chromejavascript-injection

external javascript file injection not working on chrome


I've been given this function to inject external javascript files to the rendered html:

function inject(src, cb, target){
  target = target || document.body;
  var s = document.createElement('SCRIPT');
  s.charset = 'UTF-8';

  if(typeof cb === 'function'){
    s.onload = function(){
      cb(s);
    };
    s.onreadystatechange = function () {
      (/loaded|complete/).test(s.readyState) && cb(s);
    };
  }

  s.src = src;
  target.appendChild(s);
  return s;
}

and this is the calling function:

$(function (){
  inject(swifttagurlftlpre43sc,function(script){
    var a = swifttagdiv.firstChild.attributes[2].value.substr(11);
    var is = swifttagdiv.firstChild.firstChild.src;
    var onLine = (is.substring(is.lastIndexOf('/') + 1) == 'staffonline.png');

    if (onLine) {
      $('#spanactive2').html('<span style="color: #567591;"><?php echo($content->getString('active')); ?><\/span>');
      $('#chaton2').html('<img src="/site/img/chaton.gif" alt="" />');
      $('#chat_box_timer').click(function() { eval(a); });
    } else {
      $('#live_chat_block_timer').remove();
      $('#chaton2').html('<img src="/site/img/chatoff.png" alt="" />');
    }
  });
});

And it's working fine on Firefox. It does not work on chrome though. Developer tools give me this error: Uncaught TypeError: Cannot call method 'appendChild' of null

How do I fix, or at least start to debug this?


Solution

  • My best guess was that the DOM was generated differently across browsers, and swifttagdiv.firstChild did not have attributes[2] in chrome, but did in other browsers. What it did have was the attributes['href'] property. So the solution was to change

    var a = swifttagdiv.firstChild.attributes[2].value.substr(11);

    to

    var a = swifttagdiv.firstChild.attributes['href'].value.substr(11);