Skip to content

PostWebMessage

mattkol edited this page Jul 28, 2021 · 1 revision

IPC with WebView2 using PostWebMessage requires a default JavaScript promise or similar, registering relevant ActionController(s), using the default scheme or adding a new one.

  1. PostWebMessage Promise
  2. Create & Register ActionController
  3. Make The Request

EdgeSharp provides a default JavaScript promise. This is a wrapper on "window.chrome.webview.postMessage". The promise is loaded on DOM Document Load event using CoreWeb2 API AddScriptToExecuteOnDocumentCreatedAsync.

If the promise is loaded successfully, there is nothing left for the developer to do, just use as-is. If the promise is not successfully loaded, either due to iframe or other reasons, the developer can use the promise file as an external JavaScript file in their html documents:

Like

   <head>
      ----
      <script src = "postMessagePromise.js" type = "text/javascript"/></script>
   </head>

Every request is mapped to an Action (method) defined in an ActionController class. A sample action will be (HelloWorld):

[ActionController(Name = "HelloWorldActionController", Description = "HelloWorld controller")]
public class HelloWorldActionController : ActionController
{
	[ActionRoute(Path = "/helloworld")]
	public string HelloWorld()
	{
		return "Hello, World!";
	}
}

Next, the ActionController class "HelloWorldActionController" will be registered in the Application 'ConfigureServices" method either by registering the ActionController itself or the Assembly that contains the controller.

Registering the ActionController:

public class HelloWorldApp : EdgeSharpApp
{
	public override void ConfigureServices(IServiceCollection services)
	{
		base.ConfigureServices(services);
		// other service configuration can be placed here
		
		services.AddSingleton<ActionController, HelloWorldActionController>();
	}
}

Registering the ActionController assembly:

public class HelloWorldApp : EdgeSharpApp
{
	public override void ConfigureServices(IServiceCollection services)
	{
		base.ConfigureServices(services);
		// other service configuration can be placed here

		RegisterActionControllerAssembly(services, typeof(HelloWorldActionController).Assembly);
	}
}

Using the path /helloworld to call the action HelloWorld in HelloWorldActionController above.

window.external.Execute('/helloworld' )
	.then(function (response) {
		// response : "Hello, World!";
	})
	.catch(function (error) {
		console.error(error);
	});

See usage in Win3, WinForms, Wpf