我有一个UWP解决方案,其中包含一个UWP项目(主文件MainPage,index.html,这是较高级别)和一个窗口运行时组件(主文件Bridge.cs,这是较低级别)。
加载MainPage后,它将导航到index.html,其中包含一个按钮。当用户按下按钮时,它将调用函数showMessage()(在Bridge类中定义)。到目前为止,一切正常。
但是我想从较低级别的Bridge.cs代码中调用MainPage中定义的函数,例如printMessage(),
MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
Bridge _bridge = new Bridge();
public MainPage()
{
this.InitializeComponent();
MyWebView.NavigationStarting += MyWebView_NavigationStarting;
this.Loaded += MainPage_Loaded;
}
private void _bridge_EReportFromBridge(string message)
{
Debug.WriteLine(message);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Uri navigationUri = new Uri("ms-appx-web:///Assets/html/index.html", UriKind.RelativeOrAbsolute);
Debug.WriteLine("......................navigate the url");
MyWebView.Navigate(navigationUri);
}
private void MyWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
Debug.WriteLine(".................MyWebView_NavigationStarting() is executing");
MyWebView.AddWebAllowedObject("nativeObject", _bridge);
}
public void printMessage(string message)
{
Debug.WriteLine("message: {0}", message);
}
}
index.html:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
function func1() {
// 首先判断我们对象是否正确插入
if (window.nativeObject) {
//调用的我们消息函数
window.nativeObject.showMessage("message, from index.html");
}
}
</script>
</head>
<body>
<div style="margin-top:100px">
<button id="fun1Btn" onclick="func1();">Call method 2</button>
</div>
</body>
</html>
Bridge.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Metadata;
using Windows.UI.Popups;
namespace BridgeObject
{
[AllowForWeb]
public sealed class Bridge
{
public void showMessage(string message)
{
new MessageDialog("Frome Bridge.cs: NativeMethod() is invoked!", message).ShowAsync();
// Call MainPage function printMessage(), how?
}
}
}
答案 0 :(得分:0)
如果要从Windows Runtime Component调用MainPage中定义的函数,则没有直接实现的方法。但是,您可以先通知index.html,然后通知html通过HTML调用该函数。
Bridge.cs:
通过异步方法将消息传递到index.html。
orWhere
index.html:
接收消息并通知MainPage。
[AllowForWeb]
public sealed class Bridge
{
public IAsyncOperation<string> showMessage(string message)
{
new MessageDialog("Frome Bridge.cs: NativeMethod() is invoked!", message).ShowAsync();
return Task.Run(() => {
return message;
}).AsAsyncOperation();
}
}
MainPage.xaml.cs:
首先订阅 ScriptNotify 事件以接收来自html的信息。触发后,您可以调用所需的函数。
function func1() {
if (window.nativeObject) {
var result = window.nativeObject.showMessage("message, from index.html");
result.then(function (myMessage) {
window.external.notify(myMessage); // send to MainPage
});
}
}