0

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. 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?

Nikola Stojaković
  • 2,257
  • 4
  • 27
  • 49
  • Yes, in regards to the mouse events e.g. you can add an event handler on `webBrowser.Document.Body.MouseDown += someFunc;` and use `webBrowser.Document.GetElementFromPoint(e.ClientMousePosition);` to get the clicked HTML element, then act upon it. See https://stackoverflow.com/questions/14933979/how-to-capture-click-event-for-any-button-inside-in-web-browser-control for details. – Maximilian Gerhardt Jan 07 '16 at 19:10

1 Answers1

2

Yes, you can use the WebBrowser.ObjectForScripting property to set an object that will be exposed to JavaScript as window.external. Then from within your JavaScript you can call methods on that object. 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:

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:

[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; }
}
adv12
  • 8,443
  • 2
  • 24
  • 48