简体   繁体   中英

Handle js button from C# UWP

I am new in windows and I want to handle a button that is into a WebView , when press button there is a js function to execute, and I need returned params in my C# class. In Android that is very easy, something like:

in WebView is loaded this code:

function sayHello(myParam) {
    BindJsInAndroid.sayHello(myParam);
}

<input type="button" value="My Button" onClick="sayHello('Hello world')" /><br/>

and in android code:

 WebView webView = (WebView) findViewById(R.id.web_view);
 MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(mActivityContext);
 webView.addJavascriptInterface(myJavaScriptInterface, "BindJsInAndroid");


//into MyJavaScriptInterface class
 @JavascriptInterface
        public void sayHello(String myParam) {
            //here I get myParam
        }

Is there a way to do that in UWP?

EDIT

I tried as is mentioned on msdn docs but can't get it work:

so my html src is:

<html>
<head>

<script type="text/javascript">
 function js_function() {
        bind_object.js_fun();
    }
</script>
</head>
<body>

<div>
<input type="button" value="Button" onClick="js_function()" />
</div>
</body>
</html>

and I have in my C# code:

public MainPage() {
        InitializeComponent();

     //load html src
     webView.NavigateToString(mas);

     //bind js with C#
     webView.AddWebAllowedObject("bind_object", new MyNativeClass());
        }

  [Windows.Foundation.Metadata.AllowForWeb]
    public sealed class MyNativeClass {
        public void js_fun() {
            Debug.WriteLine("get js function call");
                        }
        }

When I press button in webview I don't ge called js_fun() from C#...

There's two ways to do that on UWP.

The first one is the WebView.ScriptNotify event. The event is raised whenever you call window.external.notify from the Javascript. It's quick and painless to use, but it has only one string parameter (so you need to do some parsing if you want to squeeze multiple values inside).

The second one requires a bit more work but is closer to the Android way. You can expose an object to the Javascript by calling WebView.AddWebAllowedObject (so it works pretty much like your webView.addJavascriptInterface . But make sure to add the AllowForWeb attribute to your exposed class or it won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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