Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manually adding / removing call backs #15

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions HybridWebView/HybridWebView.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using System.Reflection;
using System.Text.Json;

namespace HybridWebView
{
Expand Down Expand Up @@ -94,13 +95,21 @@ private void InvokeDotNetMethod(JSInvokeMethodData invokeData)
throw new NotImplementedException($"The {nameof(JSInvokeTarget)} property must have a value in order to invoke a .NET method from JavaScript.");
}

var invokeMethod = JSInvokeTarget.GetType().GetMethod(invokeData.MethodName!, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod);
if (invokeMethod == null)
object containingClass = JSInvokeTarget;
MethodInfo invokeMethod = JSInvokeTarget.GetType().GetMethod(invokeData.MethodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.InvokeMethod);

if(invokeMethod is null)
{
throw new InvalidOperationException($"The method {invokeData.MethodName} couldn't be found on the {nameof(JSInvokeTarget)} of type {JSInvokeTarget.GetType().FullName}.");
(object containingClass, MethodInfo method)? localMethod = LocalRegisteredCallbacks.Where(x => x.Key.Equals(invokeData.MethodName)).Select(x => x.Value).FirstOrDefault();

if(localMethod is not null)
{
invokeMethod = localMethod.Value.method;
containingClass = localMethod.Value.containingClass;
}
}

if (invokeData.ParamValues != null && invokeMethod.GetParameters().Length != invokeData.ParamValues.Length)
if (invokeData.ParamValues is not null && invokeMethod.GetParameters().Length != invokeData.ParamValues.Length)
{
throw new InvalidOperationException($"The number of parameters on {nameof(JSInvokeTarget)}'s method {invokeData.MethodName} ({invokeMethod.GetParameters().Length}) doesn't match the number of values passed from JavaScript code ({invokeData.ParamValues.Length}).");
}
Expand All @@ -110,7 +119,24 @@ private void InvokeDotNetMethod(JSInvokeMethodData invokeData)
.Zip(invokeMethod.GetParameters(), (s, p) => JsonSerializer.Deserialize(s, p.ParameterType))
.ToArray();

var returnValue = invokeMethod.Invoke(JSInvokeTarget, paramObjectValues);
invokeMethod.Invoke(containingClass, paramObjectValues);
}


internal readonly Dictionary<string, (object containingClass, MethodInfo method)> LocalRegisteredCallbacks = new();
public void AddLocalCallback(object containingClass, string methodName)
{
MethodInfo action = containingClass.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.InvokeMethod);

if (LocalRegisteredCallbacks.ContainsKey(action.Name))
LocalRegisteredCallbacks.Remove(action.Name);

LocalRegisteredCallbacks.Add(action.Name, (containingClass, action));
}
public void RemoveLocalCallback(string methodName)
{
if (LocalRegisteredCallbacks.ContainsKey(methodName))
LocalRegisteredCallbacks.Remove(methodName);
}

private sealed class JSInvokeMethodData
Expand Down
9 changes: 9 additions & 0 deletions MauiCSharpInteropWebView/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ public MainPage()
BindingContext = this;

myHybridWebView.JSInvokeTarget = new MyJSInvokeTarget(this);

// Register in the constructor or anywhere else
myHybridWebView.AddLocalCallback(this, nameof(AddLocalCallBackTest));
}

public string CurrentPageName => $"Current hybrid page: {_currentPage}";
Expand All @@ -26,6 +29,11 @@ private async void OnSendRawMessageToJS(object sender, EventArgs e)
_ = await myHybridWebView.EvaluateJavaScriptAsync($"SendToJs('Sent from .NET, the time is: {DateTimeOffset.Now}!')");
}

private async void AddLocalCallBackTest(string message, int value)
{
WriteToLog($"I'm a .NET method called from JavaScript with message='{message}' and value={value}, using a local registration");
}

private async void OnInvokeJSMethod(object sender, EventArgs e)
{
var sum = await myHybridWebView.InvokeJsMethodAsync<int>("JsAddNumbers", 123, 456);
Expand Down Expand Up @@ -76,5 +84,6 @@ private enum HybridAppPageID
MainPage = 0,
RawMessages = 1,
MethodInvoke = 2,
ManualRegister = 3,
}
}
10 changes: 10 additions & 0 deletions MauiCSharpInteropWebView/MauiCSharpInteropWebView.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
<None Remove="Resources\Raw\hybrid_root\localMethodinvoke.html" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
</ItemGroup>
Expand All @@ -56,4 +60,10 @@
<ProjectReference Include="..\HybridWebView\HybridWebView.csproj" />
</ItemGroup>

<ItemGroup>
<MauiAsset Update="Resources\Raw\hybrid_root\localmethodinvoke.html">
<LogicalName>%(RecursiveDir)%(Filename)%(Extension)</LogicalName>
</MauiAsset>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<body>
<h1>HybridWebView demo: Main page</h1>
<div class="navBar">
Main page | <a href="/rawmessages.html">Raw messages</a> | <a href="/methodinvoke.html">Method invoke</a>
Main page | <a href="/rawmessages.html">Raw messages</a> | <a href="/methodinvoke.html">Method invoke</a> | <a href="/localmethodinvoke.html">Local method invoke</a>
</div>
<div>
Welcome to the HybridWebView demo for .NET MAUI!
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
function JsAddNumbers(a, b) {
var sum = a + b;
Log('Called from .NET with values (' + a + ', ' + b + '), and returning the sum: ' + sum);
return sum;
}

function CallDotNetMethod() {
Log('Calling a method in .NET with some parameters');

HybridWebView.SendInvokeMessageToDotNet("AddLocalCallBackTest", ["msg from js", 987]);
}
</script>
<script src="_hwv/HybridWebView.js"></script>
<script src="js/extra_code.js"></script>
<link href="styles/my-styles.css" rel="stylesheet" />
</head>
<body>
<h1>HybridWebView demo: Method invoke</h1>
<div class="navBar">
<a href="/">Main page</a> | <a href="/rawmessages.html">Raw messages</a> | <a href="/methodinvoke.html">Method invoke</a> | Local method invoke
</div>
<div>
Methods can be invoked in both directions:

<ul>
<li>JavaScript can invoke .NET methods by calling <code>HybridWebView.SendInvokeMessageToDotNet("DotNetMethodName", ["param1", 123]);</code>.</li>
<li>.NET can invoke JavaScript methods by calling <code>var sum = await webView.InvokeJsMethodAsync<int>("JsAddNumbers", 123, 456);</code>.</li>
</ul>
</div>
<div>
<button type="button" onclick="CallDotNetMethod()">Call .NET method with some parameters</button>
</div>
<h2>
JS message log:
</h2>
<div>
<textarea id="messageLog" style="width: 90%; height: 10em;"></textarea>
</div>
<script>
// Notify .NET code which page we're on
HybridWebView.SendRawMessageToDotNet("page:3");
</script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<body>
<h1>HybridWebView demo: Method invoke</h1>
<div class="navBar">
<a href="/">Main page</a> | <a href="/rawmessages.html">Raw messages</a> | Method invoke
<a href="/">Main page</a> | <a href="/rawmessages.html">Raw messages</a> | Method invoke | <a href="/localmethodinvoke.html">Local method invoke</a>
</div>
<div>
Methods can be invoked in both directions:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<body>
<h1>HybridWebView demo: Raw messages</h1>
<div class="navBar">
<a href="/">Main page</a> | Raw messages | <a href="/methodinvoke.html">Method invoke</a>
<a href="/">Main page</a> | Raw messages | <a href="/methodinvoke.html">Method invoke</a> | <a href="/localmethodinvoke.html">Local method invoke</a>
</div>
<div>
Raw messages are sent as a raw string from JavaScript to .NET with no further processing.
Expand Down