fix(windows): Fixes ScriptNotify and InvokeScript (#1354 by @benhamlin)

[skip ci]
This commit is contained in:
Ben Hamlin 2020-05-08 12:54:16 -07:00 committed by GitHub
parent b10b97646b
commit 81e0360ede
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 16 deletions

View File

@ -97,7 +97,7 @@ namespace winrt::ReactNativeWebView::implementation {
eventDataWriter.WriteObjectEnd();
});
winrt::hstring windowAlert = L"window.alert = function (msg) {window.external.notify(`{\"type\":\"alert\",\"message\":\"${msg}\"}`)};";
winrt::hstring windowAlert = L"window.alert = function (msg) {window.external.notify(`{\"type\":\"__alert\",\"message\":\"${msg}\"}`)};";
winrt::hstring postMessage = L"window.ReactNativeWebView = {postMessage: function (data) {window.external.notify(String(data))}};";
m_webView.InvokeScriptAsync(L"eval", { windowAlert + postMessage });
}
@ -119,26 +119,26 @@ namespace winrt::ReactNativeWebView::implementation {
void ReactWebView::OnScriptNotify(winrt::IInspectable const& /*sender*/, winrt::Windows::UI::Xaml::Controls::NotifyEventArgs const& args) {
winrt::JsonObject jsonObject;
if (winrt::JsonObject::TryParse(args.Value(), jsonObject)) {
if (winrt::JsonObject::TryParse(args.Value(), jsonObject) && jsonObject.HasKey(L"type")) {
auto type = jsonObject.GetNamedString(L"type");
if (type == L"alert") {
if (type == L"__alert") {
auto dialog = winrt::MessageDialog(jsonObject.GetNamedString(L"message"));
dialog.Commands().Append(winrt::UICommand(L"OK"));
dialog.ShowAsync();
return;
}
}
else {
m_reactContext.DispatchEvent(
m_webView,
L"topMessage",
[&](winrt::Microsoft::ReactNative::IJSValueWriter const& eventDataWriter) noexcept {
eventDataWriter.WriteObjectBegin();
{
WriteProperty(eventDataWriter, L"data", winrt::to_string(args.Value()));
}
eventDataWriter.WriteObjectEnd();
});
}
m_reactContext.DispatchEvent(
m_webView,
L"topMessage",
[&](winrt::Microsoft::ReactNative::IJSValueWriter const& eventDataWriter) noexcept {
eventDataWriter.WriteObjectBegin();
{
WriteProperty(eventDataWriter, L"data", winrt::to_string(args.Value()));
}
eventDataWriter.WriteObjectEnd();
});
}
} // namespace winrt::ReactNativeWebView::implementation

View File

@ -116,6 +116,7 @@ namespace winrt::ReactNativeWebView::implementation {
FrameworkElement const& view,
int64_t commandId,
winrt::IJSValueReader const& commandArgsReader) noexcept {
auto commandArgs = JSValue::ReadArrayFrom(commandArgsReader);
if (auto webView = view.try_as<winrt::WebView>()) {
switch (commandId) {
case static_cast<int64_t>(WebViewCommands::GoForward) :
@ -135,7 +136,7 @@ namespace winrt::ReactNativeWebView::implementation {
webView.Stop();
break;
case static_cast<int64_t>(WebViewCommands::InjectJavaScript) :
webView.InvokeScriptAsync(L"eval", { commandArgsReader.GetString() });
webView.InvokeScriptAsync(L"eval", { winrt::to_hstring(commandArgs[0].AsString()) });
break;
}
}