我正在开发Edge中的WebExtension和桌面应用程序之间的本机消息传递。但是无法通过desktopBridge与桌面应用程序进行通信。在下面的代码中,显示了消息框Success
,但没有显示消息框Test
。
AppServiceResponse desktopBridgeResponse = await this.desktopBridgeConnection.SendMessageAsync(testValueSet);
遇到异常“对象引用未设置为对象的实例”。
// AppService.cs
public async void Run(IBackgroundTaskInstance taskInstance)
{
if (appService.CallerPackageFamilyName == "Microsoft.MicrosoftEdge_8wekyb3d8bbwe") // App service connection from Edge
{
appServiceconnection = details.AppServiceConnection;
appServiceconnection.RequestReceived += OnRequestReceived;
try
{
// Make sure the DesktopApp.exe is in your AppX folder, if not rebuild the solution
await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
}
catch (Exception)
{
MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the DesktopApp.exe is in your AppX folder");
await dialog.ShowAsync();
}
}
else (appService.CallerPackageFamilyName == Windows.ApplicationModel.Package.Current.Id.FamilyName) // App service connection from desktopBridge App
{
desktopBridgeConnection = details.AppServiceConnection;
}
}
private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
try
{
AppServiceResponse desktopBridgeResponse = await this.desktopBridgeConnection.SendMessageAsync(testValueSet);
}
catch (Exception e)
{
var errorMessage = e.Message;
}
}
// DesktopApp.cs
[STAThread]
static void Main()
{
Thread appServiceThread = new Thread(new ThreadStart(InitializeAppServiceConnection));
appServiceThread.Start();
Application.Run();
}
static async void InitializeAppServiceConnection()
{
connection = new AppServiceConnection();
connection.AppServiceName = "example";
connection.PackageFamilyName = Package.Current.Id.FamilyName;
connection.RequestReceived += Connection_RequestReceived;
AppServiceConnectionStatus status = await connection.OpenAsync();
if (status != AppServiceConnectionStatus.Success)
{
// something went wrong ...
MessageBox.Show(status.ToString());
}
else
{
MessageBox.Show("Success");
}
}
private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
MessageBox.Show("Test");
string key = args.Request.Message.First().Key;
string value = args.Request.Message.First().Value.ToString();
}
根据Secure Input,它应该可以工作。
尽管已成功建立与应用程序服务的连接,为什么不输入Connection_RequestReceived()
?
任何帮助将不胜感激,谢谢!
更新:通过调试,我发现了以下问题:当应用程序服务从Edge收到消息时,Run()
方法将运行到“ Edge连接分支”中。接下来,执行OnRequestReceived()
,将消息发送到desktopBridge await this.desktopBridgeConnection.SendMessageAsync(testValueSet)
,但是失败。然后,再次执行Run()
并运行到“ DesktopBridge连接分支”中。此时,已经定义了desktopBridgeConnection
,但为时已晚。
我需要在输入desktopBridgeConnection
之前定义OnRequestReceived()
,以便可以在OnRequestReceived()
中使用它。但是我不知道如何实现。
答案 0 :(得分:0)
您需要在OnRequestRecived()中移动启动Fulltrust进程的代码,并等待启动的进程通过AppServiceConnection连接。然后将命令发送到启动的进程并获取响应并将其发送回页面。
请参阅我的问题和我设计的解决方案here。
基本上,我使用非持久连接。因此,您需要从content.js和background.js删除所有用于连接/断开连接的代码。这样一来,它就一直是无会话的“同步”调用。
祝你好运!