Search code examples
javascriptc#xamlpostmessage

How to catch the parent.postMessage("Hello from child window", "*") message into child


How can I catch the message in Xaml code behind(Parent window)? My child window is throwing this message

In child window,

function sendMsg() {
                var status = document.getElementById("status");
                if (parent && parent.postMessage) {
                    parent.postMessage("Hello from child window", "*");
                    status.innerText = "Sent message to parent...";
                }
            }

In Parent window (xaml.cs),

 private void button1_Click(object sender, RoutedEventArgs e)
        {
            // Get URI to navigate to  
            Uri uri = new Uri("child window url to be opened");            
            // Navigate to the desired URL by calling the .Navigate method  
            this.mybrowser.Navigate(uri);
        }

In Xaml,

 <WebBrowser Name="mybrowser" Margin="339,10,10,10" Height="396"></WebBrowser>
 <Button Content="Send Message to WebView" Margin="10,-700,736,0" Height="20" Click="Button_Click"/>

Solution

  • Finally I did it using window.external method of java script along with ObjectForScriptingHelper class.If I have a method InvokeMeFromJavascript within the class ObjectForScriptingHelper class.Create an object of this class and pass it to the property ObjectForScripting of WebBrowser control.This has in detail explanation http://www.dotnetfunda.com/articles/show/840/working-with-webbrowser-in-wpf