Monday, September 28, 2015

[JScript] Using jQuery in IE

IE is the browser we all love to hate. It's also scriptable and so inevitably ends up being considered for various tasks.

The following fragment demonstrates the first of two mechanisms I've found for instantiating jQuery in an IE session under script control.
var oIE;
  try {
    oIE = new ActiveXObject("InternetExplorer.Application");
  } catch (errIE) {
    WScript.Quit();
  }
  oIE.Visible = false;

  oIE.Navigate("http://www.example.com");
  while (oIE.Busy) {
    WScript.Sleep(100);
  }

  WScript.Sleep(1000); // could be less

  var DOM = oIE.Document;
  var scr = DOM.createElement('script');
  scr.src = "https://code.jquery.com/jquery-2.1.4.min.js";
  DOM.head.appendChild(scr);

  var $ = DOM.parentWindow.jQuery;
The above code is sliced out of a current project. We navigate to the target, create a script tag, point it at jquery's CDN, and append it to the document's head. Then we define a $ to point to oIE.Document.parentWindow.jQuery.

The same technique can be applied to any page, really. I have a bookmark in my browser that has a name of InjectjQuery and an address of
javascript:var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-2.1.4.min.js"; document.head.appendChild(script);

The second method for instantiating jQuery in IE can be found at plasticgrammer. I had difficulty with it, but got it working. It has some good things which I'll discuss in the next posting.

© Copyright Bruce M. Axtens, 2015

No comments: