问题
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