webviewwindows-runtimeuwpcircular-dependencywinrt-component

Call WebView page method from referenced WinRT Component with AllowForWeb class


I have a XAML page with WebView inside (for example MainPage.xaml). Also I have WinRT Component with class marked with [AllowForWeb] attribute. This component is referenced from project where MainPage.xaml located and in code-behind AddWebAllowedObject method is used. And I can't reference main project back because of circular dependency.

How to call MainPage.xaml.cs methods from component class? Very usual situation. Is there are some standard way to do it?

For example. I have a method inside RT component that could be called from JavaScript

     public void ShowMessage(string message)
    {
       // I want to call here function from MainPage.xaml.cs
    }

Solution

  • Thankfully to @Elvis Xia who has gived me idea, I has found a solution how to do it without C++.

    I have create a third project as Class Library. It doesn't has restrictions to use Action. This library I have referenced from main project and from WinRT component. Code of class inside library:

        public class BridgeClass
    {
        public static event Action<string> MessageReceived;
    
        public static void Broadcast(string message)
        {
            if (MessageReceived != null) MessageReceived(message);
        }
    } 
    

    Code inside main project with webview is:

      // place somewhere 
      BridgeClass.MessageReceived += ShowMessage;
    
      // ....... and add a method
       void ShowMessage(string msg)
        {
    
        }
    

    And now i can call this code from WinRT component:

     public void ShowMessage(string message)
    {
          BridgeClass.Broadcast("lalala");
    }