Cincy Steve
Cincy Steve

Reputation: 627

How to Embed jQuery in a WinForms app to Use in a WebBrowser Control

I would like to use jQuery in a WinForms WebBrowser control, but without getting access to jQuery via a link to a url (i.e. I want to embed jQuery in my app and get it from there). Is there a way to do that? If so, how does it need to be embedded (e.g. as a Content file) and what's the html to use it?

Upvotes: 0

Views: 3002

Answers (1)

Alexander Ryan Baggett
Alexander Ryan Baggett

Reputation: 2397

It seems pretty straight forward. Just grab the file, load it into a script element, and then add that to the DOM.

Here is how I would approach it:

Download it from here : https://code.jquery.com/jquery-2.2.4.min.js or here https://code.jquery.com/jquery/

load it into a file using File.ReadAllText Then insert it into the DOM.

Here is how you can do that :

    private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser wb = sender as WebBrowser;

        HtmlElement he = wb.Document.CreateElement("script");
        string jquery = System.IO.File.ReadAllText("jquery.js");
        he.InnerHtml = jquery;
        wb.Document.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, he);

    }

You could also inject it from a cdn like so :

 private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {  
        WebBrowser wb = sender as WebBrowser;

        HtmlElement he = wb.Document.CreateElement("script");
        mshtml.HTMLScriptElement script = he.DomElement as mshtml.HTMLScriptElement;
        script.src = "https://code.jquery.com/jquery-3.1.1.min.js";
        wb.Document.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, he);

    }

Upvotes: 1

Related Questions