简体   繁体   English

从C#中的WebBrowser控件获取操作

[英]Getting actions from WebBrowser control in C#

Is it possible to do something like this - for example, I have a form with a WebBrowser control and local HTML page that has some elements in it. 是否可以做这样的事情-例如,我有一个带有WebBrowser控件的表单,并且其中包含一些元素的本地HTML页面。 When user clicks on a button in a web page, form does something (for example, close application). 当用户单击网页中的按钮时,表单会执行某些操作(例如,关闭应用程序)。 Is there any way to connect that DOM actions with form events and how? 有什么方法可以将DOM操作与表单事件联系起来,如何联系?

Yes, you can use the WebBrowser.ObjectForScripting property to set an object that will be exposed to JavaScript as window.external . 是的,您可以使用WebBrowser.ObjectForScripting属性设置一个对象,该对象将作为window.external公开给JavaScript。 Then from within your JavaScript you can call methods on that object. 然后,可以从JavaScript中调用该对象上的方法。 If you need to first inject some JavaScript into the page to hook that stuff up in an HTML page you didn't write, look into the WebBrowser.DocumentCompleted event, where you can inject JavaScript into the WebBrowser.Document like so: 如果您需要先向页面中注入一些JavaScript来将未编写的HTML页面中的内容挂钩,请查看WebBrowser.DocumentCompleted事件,您可以在其中将JavaScript注入WebBrowser.Document如下所示:

private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    try
    {
        mainDoc = webBrowser.Document;
        if (mainDoc != null)
        {
            HtmlElementCollection heads = mainDoc.GetElementsByTagName("head");
            HtmlElement scriptEl = mainDoc.CreateElement("script");
            IHTMLScriptElement el = (IHTMLScriptElement)scriptEl.DomElement;
            el.text = "alert('hello world')";
            heads[0].AppendChild(scriptEl);
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
}

Edit: I neglected to mention that IHTMLScriptElement comes from COM and you'll need this code somewhere: 编辑:我忽略了提及IHTMLScriptElement来自COM,并且您将在某处需要此代码:

[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
    [DispId(1006)]
    string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM