0

I am looking for a way to trigger a custom event in javascript from C# code written in a Windows Runtime Component with the AllowForWeb Attribute. I know that the other way around works (triggering an event from javascript to C#) like this

public delegate void NotifyAppHandler( string str );

[AllowForWeb]
public sealed class WebViewInjectionObject
{
    public event NotifyAppHandler OnNotifyApp;

    public void NotifyApp( string str )
    {
        OnNotifyApp?.Invoke( str );
    }
}

You can then subscribe to the event in C# and trigger it from javascript like this

nativeObject.notifyApp(JSON.stringify(callInfo));

Where nativeObject has been injected into the WebView with AddWebAllowedObject

Now I am looking for a solution to do the opposite. I want to create an event in javascript and trigger it from C# using again the injected object from the Windows Runtime Component. You can assume that I have control over the javascript code that will run in the WebView and can make changes there if required.

Note: The need to do this quite unorthodox thing arises from the fact that I cannot use/don't want to use InvokeScriptAsync due to this issue

Corcus
  • 1,070
  • 7
  • 25
  • `InvokeScriptAsync` is the normal way to do this. Are you displaying content, do you just need JavaScript? As then you could use the Chakra engine and have more control. Otherwise, off-hand, you do have access to your C# object still, so you could create an observable collection/vector and have something react in JS to that, pick up the 'message' and then trigger your JS code. – Michael Hawker - MSFT Apr 26 '18 at 16:25
  • @MichaelHawker-MSFT The scenario is this. The `WebView` shows some html pages to the user. (This content comes from the web and should play on iOS,android and uwp so I can only request small changes to it). then it reaches a point where it needs data (from web and/or local storage) but it doesn't know how to get them. So it notifies the app. The app does some asynchronous tasks which fetch that data and then needs to send that data back to the javascript. As I said I cannot use InvokeScriptAsync due to the issue linked in my question. – Corcus Apr 27 '18 at 11:03
  • 1
    @MichaelHawker-MSFT You say `and have something react in JS to that`. That's the part I haven't got yet. At the moment, since I need to have asynchronus calls I am creating some `IAsyncOperation`s in the Windows Runtime Component and trying to use them in JS like this `nativeObject.notifyApp(somedata).then(function (dada) {... })`. Let's see if this works – Corcus Apr 27 '18 at 11:06

0 Answers0