views:

131

answers:

3

I have desktop application with WebBrowser control and try to inject JavaScript into loaded page.

For this I added two script elements:

       private static void AddJQueryElement(HtmlElement head)
       {
            HtmlElement scriptEl = head.Document.CreateElement("script");
            IHTMLScriptElement jQueryElement = (IHTMLScriptElement)scriptEl.DomElement;
            jQueryElement.src = @"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";

            head.AppendChild(scriptEl);           
        }

        private static void AddScriptElement(HtmlElement head)
        {
            HtmlElement scriptEl = head.Document.CreateElement("script");
            IHTMLScriptElement myScriptElement = (IHTMLScriptElement)scriptEl.DomElement;
            myScriptElement.src = @"file:///c:\JScript.js";
            head.AppendChild(scriptEl);
        }

how you can see first is reference to jQuery because I use it in my script. When I try to invoke function from my script using _webBrowser.Document.InvokeScript WebBrowser throws Script Error :"Object expected". and points to the line where i try to use jQuery (var tags = $("Body").find("*");).

How can I prevent this error?

Another interesting thing: if I add something like alert("hello"); to start of my function all works fine.

A: 

I guess your are missing to wait until the script is loaded. Therefore add an eventhandler like onload.

  HtmlElement scriptEl = head.Document.CreateElement("script");
  IHTMLScriptElement myScriptElement = (IHTMLScriptElement)scriptEl.DomElement;
  myScriptElement.src = @"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
  myScriptElement.onload = function(){
        // do jQuery code here or call your script init function
  };
  head.AppendChild(scriptEl);

the alert() will just block your browser, so there is enough time for your librarys to load.

Another note: onload will not work in IE. You need the onreadystatechange there like

script.onload = script.onreadystatechange = function(){
};
jAndy
I can't find IHTMLScriptElement.onload function
Orsol
The code provided is a C# code, not javaScript.
Orsol
A: 

It's possible you aren't specifying your script to run on load. alert("hello") is buying that time needed to download the script/finish building the HTML.

$(document).ready(function() {
  // Handler for .ready() called.
});
ryan
A: 

Haven't got correct answer, but have solved the problem by using local copy of jquery.min.js.

Orsol