Skip to content

Instantly share code, notes, and snippets.

@RobertBouillon
Created January 26, 2021 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertBouillon/c36069ad59775bef54dc114526a3bcf2 to your computer and use it in GitHub Desktop.
Save RobertBouillon/c36069ad59775bef54dc114526a3bcf2 to your computer and use it in GitHub Desktop.
Blazor IPC for Chromely
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TempusBlazor.Client.Interop
{
public static class HostInterop
{
private static Dictionary<string, Action<String>> _handlers = new Dictionary<string, Action<string>>();
public static bool IsHosted => JsInterop.Call<bool>("isHosted");
public static void SendCommand(string type, string content = null) => JsInterop.Invoke("sendHostCommand", type, content ?? string.Empty);
public static T SendRequest<T>(string type, string content, Action<string> callback) => JsInterop.Call<T>("sendHostRequest", type, content, callback);
[JSInvokable]
public static void HandleHostCommand(string type, string body)
{
if(!_handlers.TryGetValue(type, out var handler))
throw new Exception($"No handler was configured to receive a '{type}' command");
handler(body);
}
public static void HandleMessage(string header, Action<String> handler) => _handlers.Add(header, handler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment