#Javascript Error handling with #Chakra in C#

Microsoft’s ChakraCore DLL allows you run Javascript within C# applications using IE’s Javascript interpreter, without having to spawn an exernal process like PhantomJS. This has great applications for situations where you might want to evaluate a user-provided mathematical equation, perhaps like within a spreadsheet, or a statistical application.

The Hello world example can be cloned from Github here; https://github.com/Microsoft/Chakra-Samples/tree/master/ChakraCore%20Samples/Hello%20World/Windows/C%23

You’ll also need to get the built version of the DLL from Nuget here;

Install-Package Chakra.Core

I noticed that I had to copy the DLL from bin\x86 into the bin folder when running an application as 32 bit (A console app), and copy bin\x64 into the bin folder when running under IIS (64 bit)

One thing that I had to build myself in the C# code, was error handling. If the Javascript expression was buggy, then the result was null, with no information about why the Javascript had failed (for example, I noticed that btoa() and atob() were missing in Chakra – for base64 encoding/decoding).

So, to capture the error message, you need to add the following lines after RunScript

varerror = Native.JsRunScript(script, currentSourceContext++, “”, outresult);

JavaScriptValueexception;

Native.JsGetAndClearException(outexception);

JavaScriptValueexceptionString;

Native.JsConvertValueToString(exception, outexceptionString);

varstrEx = JavascriptValueToString(exceptionString);

Where JavascriptValueToString is defined as follows;

private static string JavascriptValueToString(JavaScriptValuevalue)

{

// Project script result in JS back to C#.

IntPtr resultPtr;

UIntPtr stringLength;

Native.JsStringToPointer(value, outresultPtr, outstringLength);

stringresultString = Marshal.PtrToStringUni(resultPtr);

return resultString;

}

我来评几句
登录后评论

已发表评论数()

相关站点

热门文章