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

十年热恋 提交于 2019-12-12 01:43:30

问题


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?


回答1:


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);

    }


来源:https://stackoverflow.com/questions/42095271/how-to-embed-jquery-in-a-winforms-app-to-use-in-a-webbrowser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!