【问题标题】:How to invoke a C# method in JS from an MAUI WebView and vice-versa如何从 MAUI WebView 调用 JS 中的 C# 方法,反之亦然
【发布时间】:2022-12-10 12:39:21
【问题描述】:
我想在 Javascript 中调用一个在 MAUI WebView 中调用 C# 代码的方法,反之亦然,我找不到任何关于此的文档。
我查看了 github 上的 following issue,但它对我没有帮助。
我该怎么做这样的互操作?
【问题讨论】:
标签:
javascript
c#
xamarin
interop
maui
【解决方案1】:
要在 MAUI WebView 中从 JavaScript 调用 C# 方法,您可以使用 WebView.EvaluateJavaScriptAsync 方法来执行调用 C# 方法的 JavaScript 代码。这是一个例子:
// In the C# code behind file for the page containing the WebView
public void MyCSharpMethod()
{
// Do something here
}
// In the JavaScript code executed by the WebView
window.external.invoke('MyCSharpMethod');
要在 MAUI WebView 中从 C# 调用 JavaScript 函数,您可以使用 WebView.InvokeScriptAsync 方法来执行 JavaScript 函数。这是一个例子:
// In the JavaScript code executed by the WebView
function myJavaScriptFunction()
{
// Do something here
}
// In the C# code behind file for the page containing the WebView
await MyWebView.InvokeScriptAsync("myJavaScriptFunction");
请注意,这些示例仅用于说明,您可能需要修改它们以适合您的特定场景。有关详细信息,请参阅 MAUI 中 WebView 类的文档。