Exemple #1
0
        public string runScript(string script)
        {
            IntPtr returnValue;

            try
            {
                JavaScriptValue result;
                JavaScriptValue promiseResult;

                if (Native.JsRunScript(script, currentSourceContext++, "", out result) != JavaScriptErrorCode.NoError)
                {
                    // Get error message and clear exception
                    JavaScriptValue exception;
                    if (Native.JsGetAndClearException(out exception) != JavaScriptErrorCode.NoError)
                    {
                        return("failed to get and clear exception");
                    }

                    JavaScriptPropertyId messageName;
                    if (Native.JsGetPropertyIdFromName("message",
                                                       out messageName) != JavaScriptErrorCode.NoError)
                    {
                        return("failed to get error message id");
                    }

                    JavaScriptValue messageValue;
                    if (Native.JsGetProperty(exception, messageName, out messageValue)
                        != JavaScriptErrorCode.NoError)
                    {
                        return("failed to get error message");
                    }

                    IntPtr  message;
                    UIntPtr length;
                    if (Native.JsStringToPointer(messageValue, out message, out length) != JavaScriptErrorCode.NoError)
                    {
                        return("failed to convert error message");
                    }

                    return(Marshal.PtrToStringUni(message));
                }

                // Execute promise tasks stored in promiseCallback
                while (promiseCallback.toIntPtr() != IntPtr.Zero)
                {
                    JavaScriptValue task = promiseCallback;
                    promiseCallback = new JavaScriptValue(IntPtr.Zero);
                    Native.JsCallFunction(task, null, 0, out promiseResult);
                }

                // Convert the return value.
                JavaScriptValue stringResult;
                UIntPtr         stringLength;
                if (Native.JsConvertValueToString(result, out stringResult) != JavaScriptErrorCode.NoError)
                {
                    return("failed to convert value to string.");
                }
                if (Native.JsStringToPointer(stringResult, out returnValue, out stringLength) != JavaScriptErrorCode.NoError)
                {
                    return("failed to convert return value.");
                }
            }
            catch (Exception e)
            {
                return("chakrahost: fatal error: internal error: " + e.Message);
            }

            return(Marshal.PtrToStringUni(returnValue));
        }