javascriptwin-universal-appchakra

How into inject javascript frameworks into ChakraBridge context?


I am trying to use math.js in my UWP app using ChakraBridge library. I referred the following link to use a javascript framework in a UWP app. http://www.codeproject.com/Articles/1060634/Using-JavaScript-frameworks-from-your-Csharp-UWP-a

But I am unable to figure out how to inject a javascirpt framework into Chakra context. The link says use the method "ReadAndExecute" or "DownloadAndExecute", but I could not find those methods in any of the classes of ChakraBridge library. So how do I inject *.js files into ChakraBridge context?


Solution

  • The link says use the method "ReadAndExecute" or "DownloadAndExecute", but I could not find those methods in any of the classes of ChakraBridge library.

    The two methods should be defined by coder. They are documented in ChakraBridge GitHub Site. And they look like below:

    async Task ReadAndExecute(string filename)
    {
        //"js" is the folder name of your javascript library.
        var script = await CoreTools.GetPackagedFileContentAsync("js", filename);
        host.RunScript(script);
    }
    
    async Task DownloadAndExecute(string url)
    {
        var script = await CoreTools.DownloadStringAsync(url);
        host.RunScript(script);
    }
    

    So, to register *.js files into ChakraBridge context. Simply call these two methods like below:

    string url = @"http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js";
    await DownloadAndExecute(url);//load math.js from remote source.
    await ReadAndExecute("math.js");//load math.js from local source.
    await ReadAndExecute("main.js");//main.js is the custom js codes. You can utilize math.js here.
    

    And here is the link to a basic demo I made:ChakraBridgeSample

    Notes:

    1. Newtonsoft.Json should be referenced in your project as pre-work. It can be installed either through Searching on Nuget Package Manager or by Nuget Package Manager Console: "Install-Package Newtonsoft.Json".
    2. The behavior of registering CommunicationManager.OnObjectReceived event is a little different from GitHub Documentation. There is no Type argument anymore(only data argument). So in javascript side,sendToHost function should look like below:

      var data = math.atan2(3, -3) / math.pi;
      // "Double" should match the typeof(Double) in C# side. Capitalizing is necessary.
      sendToHost(JSON.stringify(data), "Double");