I'm using axWebBrowser and I need to make a script work which works when selected item of a listbox is changed.
In default webBrowser control there is a method like;
WebBrowserEx1.Document.InvokeScript("script")
But in axWebBrowser I can not work any script! And there is no documentation about this control.
Anyone knows how ?
A late answer, but hopefully still may help someone. There is a number of ways to invoke a script when using WebBrowser ActiveX control. The same techniques can also be used with WinForms version of WebBrowser control (via webBrowser.HtmlDocument.DomDocument) and with WPF version (via webBrowser.Document):
void CallScript(SHDocVw.WebBrowser axWebBrowser)
{
//
// Using C# dynamics, which maps to COM's IDispatch::GetIDsOfNames,
// IDispatch::Invoke
//
dynamic htmlDocument = axWebBrowser.Document;
dynamic htmlWindow = htmlDocument.parentWindow;
// make sure the web page has at least one <script> tag for eval to work
htmlDocument.body.appendChild(htmlDocument.createElement("script"));
// can call any DOM window method
htmlWindow.alert("hello from web page!");
// call a global JavaScript function, e.g.:
// <script>function TestFunc(arg) { alert(arg); }</script>
htmlWindow.TestFunc("Hello again!");
// call any JavaScript via "eval"
var result = (bool)htmlWindow.eval("(function() { return confirm('Continue?'); })()");
MessageBox.Show(result.ToString());
//
// Using .NET reflection:
//
object htmlWindowObject = GetProperty(axWebBrowser.Document, "parentWindow");
// call a global JavaScript function
InvokeScript(htmlWindowObject, "TestFunc", "Hello again!");
// call any JavaScript via "eval"
result = (bool)InvokeScript(htmlWindowObject, "eval", "(function() { return confirm('Continue?'); })()");
MessageBox.Show(result.ToString());
}
static object GetProperty(object callee, string property)
{
return callee.GetType().InvokeMember(property,
BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public,
null, callee, new Object[] { });
}
static object InvokeScript(object callee, string method, params object[] args)
{
return callee.GetType().InvokeMember(method,
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public,
null, callee, args);
}
There has to be at least one <script>
tag for JavaScript's eval
to work, which can be injected as shown above.
Alternatively, JavaScript engine can be initialized asynchronously with something like webBrowser.Document.InvokeScript("setTimer", new[] { "window.external.notifyScript()", "1" })
or webBrowser.Navigate("javascript:(window.external.notifyScript(), void(0))")
.
来源:https://stackoverflow.com/questions/15273311/how-to-invoke-scripts-work-in-mshtml