Languages

Menu
Sites
Language
How to use AddJavaScriptMessageHandler?

How to use AddJavaScriptMessageHandler of webview to send message from JavaScript?

c#

try
{
    this.control = (T.WebView)this.NativeView;
    if (this.control != null)
    {
        bool bok = this.control.AddJavaScriptMessageHandler("test", new T.JavaScriptMessageHandler(this.OnJavaScriptCall));
        System.Diagnostics.Debug.WriteLine(bok);

    }
    
}
catch
{
}

JavaScript:

<script type="text/javascript">
    alert(test);
</script>

test is null on Html.... who can help me?

Responses

5 Replies
Armaan-Ul- Islam

You can only check the API Documentations for Xamarin.Forms as Tizen.NET Supports Xamarin.Forms only.

This guide seemed relevant:

https://developer.xamarin.com/guides/xamarin-forms/user-interface/webview/

Along with samples for webview:

https://developer.xamarin.com/samples/xamarin-forms/WorkingWithWebview/

Check Xamarin.Forms Section only.

Youngha Jung
window.test.postMessage("Test message");

First of all, `AddJavaScriptMessageHandler` has to be called before `LoadUrl` method.

And then, you can send message from your javascript to native app using `postMessage.`

 

 

Dmitry Kroz

Hello!
I'm using a hybrid webview in the wearable app (.net) and I'm having issue with 'AddJavaScriptMessageHandler'. It works fine (I can post messages) when webview appears for the first time, but when user goes back to previous screen and then returns to the webview - it seems like webview has been reloaded, but 'AddJavaScriptMessageHandler' returns 'false'.
I understand that this method has to be calls before 'LoadUrl' and I do this, but for some reason it works only once during the app lifecycle - when I load webview for the very first time.


 

Marco Buettner

In your case the test is a variable and isnt initial correct thats why the alert will show "null".

<script type="text/javascript">
    alert(test);
</script>

You can use

<script type="text/javascript">
    alert('test');
</script>

or

 

<script type="text/javascript">
    const test = 'testmessage';
    alert(test);
</script>