Capture a custom Javascript event in C# WPF mshtml WebBrowser control












0















I'm unable to capture a custom Javascript event in a C# WPF mshtml WebBrowser control. I've created the example code below. A button click raises a custom event. I realise that there are easy ways to capture a button click event. I need to use a custom event. I've used a button just for this example and testing. What am I doing wrong?



XAML file:



<Window x:Class="WebEvent2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WebBrowser Name="webBrowser1" Loaded="webBrowser1_Loaded" LoadCompleted="webBrowser1_LoadCompleted"></WebBrowser>
</Grid>
</Window>


C# file:



namespace WebEvent2{
public partial class MainWindow : Window{
public MainWindow(){
InitializeComponent();
}

private void webBrowser1_Loaded(object sender, RoutedEventArgs e{
webBrowser1.Navigate(@"file:///D:/test.html");
}

private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e){
try{
var evtListener = new EventListener();
var window = ((IHTMLDocument2)webBrowser1.Document).parentWindow as IHTMLWindow3;
window.attachEvent("MyCustomEvent", evtListener);

// Also not working:
// ((HTMLDocument)webBrowser1.Document).attachEvent("MyCustomEvent", evtListener);
}catch (UnauthorizedAccessException err){
Console.WriteLine("OOPS: " + err);
}
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class EventListener{
[DispId(0)]
public void handler(IHTMLEventObj evt){
MessageBox.Show("message received");
}
}
}
}


HTML file:



<html>
<head>
<title>Test page</title>
<script>
function sendCustomEvent() {
var event;
if (typeof(Event) === 'function') {
event = new Event('MyCustomEvent');
} else {
event = document.createEvent('HTMLEvents');
event.initEvent('MyCustomEvent', true, false);
}

document.dispatchEvent(event);
}
</script>
</head>
<body>
<button onclick="sendCustomEvent()">Send custom event</button>
</body>
</html>









share|improve this question





























    0















    I'm unable to capture a custom Javascript event in a C# WPF mshtml WebBrowser control. I've created the example code below. A button click raises a custom event. I realise that there are easy ways to capture a button click event. I need to use a custom event. I've used a button just for this example and testing. What am I doing wrong?



    XAML file:



    <Window x:Class="WebEvent2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
    <WebBrowser Name="webBrowser1" Loaded="webBrowser1_Loaded" LoadCompleted="webBrowser1_LoadCompleted"></WebBrowser>
    </Grid>
    </Window>


    C# file:



    namespace WebEvent2{
    public partial class MainWindow : Window{
    public MainWindow(){
    InitializeComponent();
    }

    private void webBrowser1_Loaded(object sender, RoutedEventArgs e{
    webBrowser1.Navigate(@"file:///D:/test.html");
    }

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e){
    try{
    var evtListener = new EventListener();
    var window = ((IHTMLDocument2)webBrowser1.Document).parentWindow as IHTMLWindow3;
    window.attachEvent("MyCustomEvent", evtListener);

    // Also not working:
    // ((HTMLDocument)webBrowser1.Document).attachEvent("MyCustomEvent", evtListener);
    }catch (UnauthorizedAccessException err){
    Console.WriteLine("OOPS: " + err);
    }
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    public class EventListener{
    [DispId(0)]
    public void handler(IHTMLEventObj evt){
    MessageBox.Show("message received");
    }
    }
    }
    }


    HTML file:



    <html>
    <head>
    <title>Test page</title>
    <script>
    function sendCustomEvent() {
    var event;
    if (typeof(Event) === 'function') {
    event = new Event('MyCustomEvent');
    } else {
    event = document.createEvent('HTMLEvents');
    event.initEvent('MyCustomEvent', true, false);
    }

    document.dispatchEvent(event);
    }
    </script>
    </head>
    <body>
    <button onclick="sendCustomEvent()">Send custom event</button>
    </body>
    </html>









    share|improve this question



























      0












      0








      0








      I'm unable to capture a custom Javascript event in a C# WPF mshtml WebBrowser control. I've created the example code below. A button click raises a custom event. I realise that there are easy ways to capture a button click event. I need to use a custom event. I've used a button just for this example and testing. What am I doing wrong?



      XAML file:



      <Window x:Class="WebEvent2.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525">
      <Grid>
      <WebBrowser Name="webBrowser1" Loaded="webBrowser1_Loaded" LoadCompleted="webBrowser1_LoadCompleted"></WebBrowser>
      </Grid>
      </Window>


      C# file:



      namespace WebEvent2{
      public partial class MainWindow : Window{
      public MainWindow(){
      InitializeComponent();
      }

      private void webBrowser1_Loaded(object sender, RoutedEventArgs e{
      webBrowser1.Navigate(@"file:///D:/test.html");
      }

      private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e){
      try{
      var evtListener = new EventListener();
      var window = ((IHTMLDocument2)webBrowser1.Document).parentWindow as IHTMLWindow3;
      window.attachEvent("MyCustomEvent", evtListener);

      // Also not working:
      // ((HTMLDocument)webBrowser1.Document).attachEvent("MyCustomEvent", evtListener);
      }catch (UnauthorizedAccessException err){
      Console.WriteLine("OOPS: " + err);
      }
      }

      [ComVisible(true)]
      [ClassInterface(ClassInterfaceType.AutoDispatch)]
      public class EventListener{
      [DispId(0)]
      public void handler(IHTMLEventObj evt){
      MessageBox.Show("message received");
      }
      }
      }
      }


      HTML file:



      <html>
      <head>
      <title>Test page</title>
      <script>
      function sendCustomEvent() {
      var event;
      if (typeof(Event) === 'function') {
      event = new Event('MyCustomEvent');
      } else {
      event = document.createEvent('HTMLEvents');
      event.initEvent('MyCustomEvent', true, false);
      }

      document.dispatchEvent(event);
      }
      </script>
      </head>
      <body>
      <button onclick="sendCustomEvent()">Send custom event</button>
      </body>
      </html>









      share|improve this question
















      I'm unable to capture a custom Javascript event in a C# WPF mshtml WebBrowser control. I've created the example code below. A button click raises a custom event. I realise that there are easy ways to capture a button click event. I need to use a custom event. I've used a button just for this example and testing. What am I doing wrong?



      XAML file:



      <Window x:Class="WebEvent2.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525">
      <Grid>
      <WebBrowser Name="webBrowser1" Loaded="webBrowser1_Loaded" LoadCompleted="webBrowser1_LoadCompleted"></WebBrowser>
      </Grid>
      </Window>


      C# file:



      namespace WebEvent2{
      public partial class MainWindow : Window{
      public MainWindow(){
      InitializeComponent();
      }

      private void webBrowser1_Loaded(object sender, RoutedEventArgs e{
      webBrowser1.Navigate(@"file:///D:/test.html");
      }

      private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e){
      try{
      var evtListener = new EventListener();
      var window = ((IHTMLDocument2)webBrowser1.Document).parentWindow as IHTMLWindow3;
      window.attachEvent("MyCustomEvent", evtListener);

      // Also not working:
      // ((HTMLDocument)webBrowser1.Document).attachEvent("MyCustomEvent", evtListener);
      }catch (UnauthorizedAccessException err){
      Console.WriteLine("OOPS: " + err);
      }
      }

      [ComVisible(true)]
      [ClassInterface(ClassInterfaceType.AutoDispatch)]
      public class EventListener{
      [DispId(0)]
      public void handler(IHTMLEventObj evt){
      MessageBox.Show("message received");
      }
      }
      }
      }


      HTML file:



      <html>
      <head>
      <title>Test page</title>
      <script>
      function sendCustomEvent() {
      var event;
      if (typeof(Event) === 'function') {
      event = new Event('MyCustomEvent');
      } else {
      event = document.createEvent('HTMLEvents');
      event.initEvent('MyCustomEvent', true, false);
      }

      document.dispatchEvent(event);
      }
      </script>
      </head>
      <body>
      <button onclick="sendCustomEvent()">Send custom event</button>
      </body>
      </html>






      javascript c# wpf mshtml






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 8:05







      Don

















      asked Nov 22 '18 at 6:08









      DonDon

      1717




      1717
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I was able to achieve the required functionality by using the WebBrowser controls 'ObjectForScripting' property. Nice and simple.



          XAML remains the same as above.



          WebInterface.cs:



          namespace WebEvent2
          {
          [System.Runtime.InteropServices.ComVisibleAttribute(true)]
          public class WebInterface
          {
          public void callMe()
          {
          MessageBox.Show("hello");
          }
          }
          }


          MainWindow.xaml.cs:



          namespace WebEvent2
          {
          public partial class MainWindow : Window
          {
          public MainWindow()
          {
          InitializeComponent();
          }

          WebInterface wi = new WebInterface();

          private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
          {
          webBrowser1.ObjectForScripting = wi;
          webBrowser1.Navigate(@"file:///D:/test.html");
          }
          }
          }


          test.html:



          <html>
          <head>
          <title>Test page</title>
          </head>
          <body>
          <button onclick="window.external.callMe()">Send custom event</button>
          </body>
          </html>





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424818%2fcapture-a-custom-javascript-event-in-c-sharp-wpf-mshtml-webbrowser-control%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I was able to achieve the required functionality by using the WebBrowser controls 'ObjectForScripting' property. Nice and simple.



            XAML remains the same as above.



            WebInterface.cs:



            namespace WebEvent2
            {
            [System.Runtime.InteropServices.ComVisibleAttribute(true)]
            public class WebInterface
            {
            public void callMe()
            {
            MessageBox.Show("hello");
            }
            }
            }


            MainWindow.xaml.cs:



            namespace WebEvent2
            {
            public partial class MainWindow : Window
            {
            public MainWindow()
            {
            InitializeComponent();
            }

            WebInterface wi = new WebInterface();

            private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
            {
            webBrowser1.ObjectForScripting = wi;
            webBrowser1.Navigate(@"file:///D:/test.html");
            }
            }
            }


            test.html:



            <html>
            <head>
            <title>Test page</title>
            </head>
            <body>
            <button onclick="window.external.callMe()">Send custom event</button>
            </body>
            </html>





            share|improve this answer




























              0














              I was able to achieve the required functionality by using the WebBrowser controls 'ObjectForScripting' property. Nice and simple.



              XAML remains the same as above.



              WebInterface.cs:



              namespace WebEvent2
              {
              [System.Runtime.InteropServices.ComVisibleAttribute(true)]
              public class WebInterface
              {
              public void callMe()
              {
              MessageBox.Show("hello");
              }
              }
              }


              MainWindow.xaml.cs:



              namespace WebEvent2
              {
              public partial class MainWindow : Window
              {
              public MainWindow()
              {
              InitializeComponent();
              }

              WebInterface wi = new WebInterface();

              private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
              {
              webBrowser1.ObjectForScripting = wi;
              webBrowser1.Navigate(@"file:///D:/test.html");
              }
              }
              }


              test.html:



              <html>
              <head>
              <title>Test page</title>
              </head>
              <body>
              <button onclick="window.external.callMe()">Send custom event</button>
              </body>
              </html>





              share|improve this answer


























                0












                0








                0







                I was able to achieve the required functionality by using the WebBrowser controls 'ObjectForScripting' property. Nice and simple.



                XAML remains the same as above.



                WebInterface.cs:



                namespace WebEvent2
                {
                [System.Runtime.InteropServices.ComVisibleAttribute(true)]
                public class WebInterface
                {
                public void callMe()
                {
                MessageBox.Show("hello");
                }
                }
                }


                MainWindow.xaml.cs:



                namespace WebEvent2
                {
                public partial class MainWindow : Window
                {
                public MainWindow()
                {
                InitializeComponent();
                }

                WebInterface wi = new WebInterface();

                private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
                {
                webBrowser1.ObjectForScripting = wi;
                webBrowser1.Navigate(@"file:///D:/test.html");
                }
                }
                }


                test.html:



                <html>
                <head>
                <title>Test page</title>
                </head>
                <body>
                <button onclick="window.external.callMe()">Send custom event</button>
                </body>
                </html>





                share|improve this answer













                I was able to achieve the required functionality by using the WebBrowser controls 'ObjectForScripting' property. Nice and simple.



                XAML remains the same as above.



                WebInterface.cs:



                namespace WebEvent2
                {
                [System.Runtime.InteropServices.ComVisibleAttribute(true)]
                public class WebInterface
                {
                public void callMe()
                {
                MessageBox.Show("hello");
                }
                }
                }


                MainWindow.xaml.cs:



                namespace WebEvent2
                {
                public partial class MainWindow : Window
                {
                public MainWindow()
                {
                InitializeComponent();
                }

                WebInterface wi = new WebInterface();

                private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
                {
                webBrowser1.ObjectForScripting = wi;
                webBrowser1.Navigate(@"file:///D:/test.html");
                }
                }
                }


                test.html:



                <html>
                <head>
                <title>Test page</title>
                </head>
                <body>
                <button onclick="window.external.callMe()">Send custom event</button>
                </body>
                </html>






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 0:02









                DonDon

                1717




                1717






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424818%2fcapture-a-custom-javascript-event-in-c-sharp-wpf-mshtml-webbrowser-control%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Costa Masnaga

                    Fotorealismo

                    Sidney Franklin