forked from dotnet/maui
/
BlazorWebViewHandler.Tizen.cs
196 lines (172 loc) · 5.94 KB
/
BlazorWebViewHandler.Tizen.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Maui;
using Microsoft.Maui.Dispatching;
using Microsoft.Maui.Handlers;
using Tizen.NUI;
using NWebView = Tizen.NUI.BaseComponents.WebView;
namespace Microsoft.AspNetCore.Components.WebView.Maui
{
/// <summary>
/// The Tizen <see cref="ViewHandler"/> for <see cref="BlazorWebView"/>.
/// </summary>
public partial class BlazorWebViewHandler : ViewHandler<IBlazorWebView, NWebView>
{
private const string BlazorWebViewIdentifier = "BlazorWebView:";
private const string UserAgentHeaderKey = "User-Agent";
private const string AppOrigin = "http://0.0.0.0/";
private const string BlazorInitScript = @"
window.__receiveMessageCallbacks = [];
window.__dispatchMessageCallback = function(message) {
window.__receiveMessageCallbacks.forEach(function(callback) { callback(message); });
};
window.external = {
sendMessage: function(message) {
window.BlazorHandler.postMessage(message);
},
receiveMessage: function(callback) {
window.__receiveMessageCallbacks.push(callback);
}
};
Blazor.start();
(function () {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
})();
";
static private Dictionary<string, WeakReference<BlazorWebViewHandler>> s_webviewHandlerTable = new Dictionary<string, WeakReference<BlazorWebViewHandler>>();
private TizenWebViewManager? _webviewManager;
private bool RequiredStartupPropertiesSet =>
//_webview != null &&
HostPage != null &&
Services != null;
/// <inheritdoc />
protected override NWebView CreatePlatformView()
{
return new NWebView()
{
MouseEventsEnabled = true,
KeyEventsEnabled = true,
};
}
/// <inheritdoc />
protected override void ConnectHandler(NWebView platformView)
{
platformView.PageLoadFinished += OnLoadFinished;
platformView.Context.RegisterHttpRequestInterceptedCallback(OnRequestInterceptStaticCallback);
platformView.AddJavaScriptMessageHandler("BlazorHandler", PostMessageFromJS);
platformView.UserAgent += $" {BlazorWebViewIdentifier}{GetHashCode()}";
s_webviewHandlerTable[GetHashCode().ToString()] = new WeakReference<BlazorWebViewHandler>(this);
}
/// <inheritdoc />
protected override void DisconnectHandler(NWebView platformView)
{
platformView.PageLoadFinished -= OnLoadFinished;
base.DisconnectHandler(platformView);
s_webviewHandlerTable.Remove(GetHashCode().ToString());
}
private void PostMessageFromJS(string message)
{
_webviewManager!.MessageReceivedInternal(new Uri(PlatformView.Url), message);
}
private void OnLoadFinished(object? sender, WebViewPageLoadEventArgs e)
{
//FocusManager.Instance.SetCurrentFocusView(NativeView);
var url = PlatformView.Url;
if (url == AppOrigin)
PlatformView.EvaluateJavaScript(BlazorInitScript);
}
private static void OnRequestInterceptStaticCallback(WebHttpRequestInterceptor interceptor)
{
if (interceptor.Headers.TryGetValue(UserAgentHeaderKey, out var agent))
{
var idx = agent.IndexOf(BlazorWebViewIdentifier);
if (idx >= 0)
{
var webviewKey = agent.Substring(idx + BlazorWebViewIdentifier.Length);
if (s_webviewHandlerTable.TryGetValue(webviewKey, out var weakHandler)
&& weakHandler.TryGetTarget(out var handler))
{
handler.OnRequestInterceptCallback(interceptor);
return;
}
}
}
interceptor.Ignore();
}
private void OnRequestInterceptCallback(WebHttpRequestInterceptor interceptor)
{
var url = interceptor.Url;
if (url.StartsWith(AppOrigin))
{
var allowFallbackOnHostPage = url.EndsWith("/");
url = QueryStringHelper.RemovePossibleQueryString(url);
if (_webviewManager!.TryGetResponseContentInternal(url, allowFallbackOnHostPage, out var statusCode, out var statusMessage, out var content, out var headers))
{
var header = $"HTTP/1.0 200 OK\r\n";
foreach (var item in headers)
{
header += $"{item.Key}:{item.Value}\r\n";
}
header += "\r\n";
MemoryStream memstream = new MemoryStream();
content.CopyTo(memstream);
interceptor.SetResponse(header, memstream.ToArray());
return;
}
}
interceptor.Ignore();
}
private void StartWebViewCoreIfPossible()
{
if (!RequiredStartupPropertiesSet ||
_webviewManager != null)
{
return;
}
if (PlatformView == null)
{
throw new InvalidOperationException($"Can't start {nameof(BlazorWebView)} without platform web view instance.");
}
// We assume the host page is always in the root of the content directory, because it's
// unclear there's any other use case. We can add more options later if so.
var contentRootDir = System.IO.Path.GetDirectoryName(HostPage!) ?? string.Empty;
var hostPageRelativePath = System.IO.Path.GetRelativePath(contentRootDir, HostPage!);
var fileProvider = VirtualView.CreateFileProvider(contentRootDir);
_webviewManager = new TizenWebViewManager(
this,
PlatformView,
Services!,
new MauiDispatcher(Services!.GetRequiredService<IDispatcher>()),
fileProvider,
VirtualView.JSComponents,
contentRootDir,
hostPageRelativePath);
StaticContentHotReloadManager.AttachToWebViewManagerIfEnabled(_webviewManager);
VirtualView.BlazorWebViewInitializing(new BlazorWebViewInitializingEventArgs());
VirtualView.BlazorWebViewInitialized(new BlazorWebViewInitializedEventArgs
{
WebView = PlatformView,
});
if (RootComponents != null)
{
foreach (var rootComponent in RootComponents)
{
// Since the page isn't loaded yet, this will always complete synchronously
_ = rootComponent.AddToWebViewManagerAsync(_webviewManager);
}
}
_webviewManager.Navigate("/");
}
internal IFileProvider CreateFileProvider(string contentRootDir)
{
return new TizenMauiAssetFileProvider(contentRootDir);
}
}
}