Skip to content

Commit

Permalink
Merge pull request #95 from egvijayanand/working
Browse files Browse the repository at this point in the history
HybridWebView sample updated to .NET MAUI 9 RC1
  • Loading branch information
egvijayanand authored Sep 12, 2024
2 parents c1f65f5 + 103b847 commit e23c5f0
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 60 deletions.
2 changes: 1 addition & 1 deletion src/NET_9/HybridWebViewApp/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ public App()
}

protected override Window CreateWindow(IActivationState? activationState)
=> new Window(new MainPage()) { Title = "HybridWebViewApp" };
=> new MainWindow();
}
}
14 changes: 14 additions & 0 deletions src/NET_9/HybridWebViewApp/MainWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Window
x:Class="HybridWebViewApp.MainWindow"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vw="clr-namespace:HybridWebViewApp.Views"
Title="HybridWebViewApp"
mc:Ignorable="d">
<Window.Page>
<vw:MainPage />
</Window.Page>
</Window>
15 changes: 15 additions & 0 deletions src/NET_9/HybridWebViewApp/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace HybridWebViewApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

public MainWindow(Page page) : base(page)
{
InitializeComponent();
}
}
}
41 changes: 23 additions & 18 deletions src/NET_9/HybridWebViewApp/Resources/Raw/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
<link rel="stylesheet" href="css/app.css" />
<link rel="icon" href="data:,">
<script src="scripts/hwv.js"></script>
</head>
<body>
<h3>HybridWebView App!</h3>
<div style="margin-left: 10px;">
<input type="text" id="message" class="text-black" placeholder="Enter your message here" maxlength="50" />
<button type="button" id="send" class="btn btn-primary" disabled>Send to .NET</button>
</div>
<div style="margin-top: 20px;">
Messages from .NET: <textarea readonly id="msgFromCS" style="width: 80%; height: 300px;"></textarea>
</div>
<script>
window.addEventListener(
"HybridWebViewMessageReceived",
Expand All @@ -19,35 +29,30 @@
msgFromCS.scrollTop = msgFromCS.scrollHeight;
});

function onChanged() {
var message = document.getElementById("message");
var send = document.getElementById("send");
let message = document.getElementById("message");
let send = document.getElementById("send");

message.addEventListener("input", function() {
if (message.value == '') {
send.disabled = true;
} else {
send.disabled = false;
}
}
});

message.addEventListener("keypress", function(e) {
console.log(e.key);
if (e.key === "Enter") {
send.click();
}
});

function onSend() {
var message = document.getElementById("message");
var send = document.getElementById("send");
send.addEventListener("click", function() {
window.HybridWebView.SendRawMessage(message.value);
message.value = '';
send.disabled = true;
message.focus();
}
});
</script>
</head>
<body>
<h3>HybridWebView App!</h3>
<div style="margin-left: 10px;">
<input type="text" id="message" class="text-black" placeholder="Enter your message here" maxlength="50" oninput="onChanged();" />
<button type="button" id="send" class="btn btn-primary" onclick="onSend();" disabled>Send to .NET</button>
</div>
<div style="margin-top: 20px;">
Messages from .NET: <textarea readonly id="msgFromCS" style="width: 80%; height: 300px;"></textarea>
</div>
</body>
</html>
95 changes: 62 additions & 33 deletions src/NET_9/HybridWebViewApp/Resources/Raw/wwwroot/scripts/hwv.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,78 @@
function HybridWebViewInit()
{
function DispatchHybridWebViewMessage(message) {
const event = new CustomEvent("HybridWebViewMessageReceived", { detail: { message: message } });
window.dispatchEvent(event);
}
window.HybridWebView = {
"Init": function () {
function DispatchHybridWebViewMessage(message) {
const event = new CustomEvent("HybridWebViewMessageReceived", { detail: { message: message } });
window.dispatchEvent(event);
}

if (window.chrome && window.chrome.webview) {
// Windows WebView2
window.chrome.webview.addEventListener('message', arg => {
DispatchHybridWebViewMessage(arg.data);
});
}
else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webwindowinterop) {
// iOS and MacCatalyst WKWebView
window.external = {
"receiveMessage": message => {
DispatchHybridWebViewMessage(message);
}
};
}
else {
// Android WebView
window.addEventListener('message', arg => {
DispatchHybridWebViewMessage(arg.data);
});
}
}
if (window.chrome && window.chrome.webview) {
// Windows WebView2
window.chrome.webview.addEventListener('message', arg => {
DispatchHybridWebViewMessage(arg.data);
});
}
else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webwindowinterop) {
// iOS and MacCatalyst WKWebView
window.external = {
"receiveMessage": message => {
DispatchHybridWebViewMessage(message);
}
};
}
else {
// Android WebView
window.addEventListener('message', arg => {
DispatchHybridWebViewMessage(arg.data);
});
}
},

window.HybridWebView =
{
"SendRawMessage": function (message) {
window.HybridWebView.__SendMessageInternal('RawMessage', message);
},

"__SendMessageInternal": function (type, message) {

const messageToSend = type + '|' + message;

if (window.chrome && window.chrome.webview) {
// Windows WebView2
window.chrome.webview.postMessage(message);
window.chrome.webview.postMessage(messageToSend);
}
else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webwindowinterop) {
// iOS and MacCatalyst WKWebView
window.webkit.messageHandlers.webwindowinterop.postMessage(message);
window.webkit.messageHandlers.webwindowinterop.postMessage(messageToSend);
}
else {
// Android WebView
hybridWebViewHost.sendRawMessage(message);
hybridWebViewHost.sendMessage(messageToSend);
}
},

"InvokeMethod": function (taskId, methodName, args) {
if (methodName[Symbol.toStringTag] === 'AsyncFunction') {
// For async methods, we need to call the method and then trigger the callback when it's done
const asyncPromise = methodName(...args);
asyncPromise
.then(asyncResult => {
window.HybridWebView.__TriggerAsyncCallback(taskId, asyncResult);
})
.catch(error => console.error(error));
} else {
// For sync methods, we can call the method and trigger the callback immediately
const syncResult = methodName(...args);
window.HybridWebView.__TriggerAsyncCallback(taskId, syncResult);
}
},

"__TriggerAsyncCallback": function (taskId, result) {
// Make sure the result is a string
if (result && typeof (result) !== 'string') {
result = JSON.stringify(result);
}

window.HybridWebView.__SendMessageInternal('InvokeMethodCompleted', taskId + '|' + result);
}
}

HybridWebViewInit();
window.HybridWebView.Init();
2 changes: 1 addition & 1 deletion src/NET_9/HybridWebViewApp/Views/MainPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
Light={StaticResource Primary}}">

<Label
x:Name="VersionLabel"
x:Name="versionLabel"
HorizontalOptions="Center"
TextColor="{StaticResource White}"
VerticalOptions="Center" />
Expand Down
17 changes: 10 additions & 7 deletions src/NET_9/HybridWebViewApp/Views/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ public partial class MainPage : ContentPage
public MainPage()
{
InitializeComponent();
message.ReturnCommand = new Command(SendMessage);
var version = typeof(MauiApp).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
VersionLabel.Text = $".NET MAUI ver. {version?[..version.IndexOf('+')]}";
versionLabel.Text = $".NET MAUI ver. {version?[..version.IndexOf('+')]}";
}

private void OnSendClicked(object sender, EventArgs e)
{
hwv.SendRawMessage(message.Text);
message.Text = string.Empty;
message.Focus();
}
private void OnSendClicked(object sender, EventArgs e) => SendMessage();

private async void OnRawMessageReceived(object sender, HybridWebViewRawMessageReceivedEventArgs e)
{
Expand All @@ -27,5 +23,12 @@ private void OnMessageChanged(object sender, TextChangedEventArgs e)
{
send.IsEnabled = message.Text.Length > 0;
}

private void SendMessage()
{
hwv.SendRawMessage(message.Text);
message.Text = string.Empty;
message.Focus();
}
}
}

0 comments on commit e23c5f0

Please sign in to comment.