Code Monkey home page Code Monkey logo

chakra-samples's Introduction

Chakra-Samples

Repository for Chakra and ChakraCore samples.

Terms of Use

By downloading and running this project, you agree to the license terms of the third party application software, Microsoft products, and components to be installed.

The third party software and products are provided to you by third parties. You are responsible for reading and accepting the relevant license terms for all software that will be installed. Microsoft grants you no rights to third party software.

License

Unless otherwise mentioned, the samples are released under the MIT license.

The MIT License (MIT)

Copyright (c) Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Help us improve our samples

Help us improve out samples by sending us a pull-request or opening a GitHub Issue

chakra-samples's People

Contributors

capfei avatar ctaggart avatar juliusl avatar kfarnung avatar liminzhu avatar microsoft-github-policy-service[bot] avatar obastemur avatar rub8n avatar taritsyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chakra-samples's Issues

[JsGetArrayBufferStorage] use byte[] as output, should be an IntPtr

the wrapper in sample code uses byte[] as output, however, this returns only the first element of the native storage. should use IntPtr as it's actually a pointer. I've changed it in my library to get the actual data.
same issue in JsGetTypedArrayStorage and JsGetDataViewStorage

Original: internal static extern JavaScriptErrorCode JsGetArrayBufferStorage(JavaScriptValue arrayBuffer, out byte[] data, out uint bufferLength);

Modified: internal static extern JavaScriptErrorCode JsGetArrayBufferStorage(JavaScriptValue arrayBuffer, out IntPtr data, out uint bufferLength);

Circular reference btw an object and a function object

I have an implementation for say, a button control which gets created when I create an instance in JS as follows:
var btn = new Button();

We have set a function object to handle the onclick functionality for the button as follows:
btn.clickEvent = function(){
btn.setText = "new Text";//a property to set the text for the button
}

This function object is held by the button control which when clicked executes the function object.

Upon referring to the btn instance inside the function object is creating a circular reference between the button and the function object. So the btn instance is never collected by the GC.

If the reference to the button is removed from the function object, the button is getting collected by the GC. Is there a way to ensure that one reference could be made a weak reference so that the button instance is always garbage collected?

Bad Image Format HRESULT: 0x8007000B with C# and how to mitigate it

Hi,

I encountered a strange BadImageFormat Exception when trying to build the HelloWorld Demo.
My setup is VS2015 Debug x64, and before setting up this demo project I compiled the ChakraCore.dll by following the Wiki-tutorial.

This happened when I tried to run the console app:

exception

This was very unusual because my Debug-Build is also x64 just like the ChakraCore.dll from the C++ project.

After some experimenting I changed the Platform Target from Any CPU to x64 in Project's Build-Properties:

target

Now everything worked as expected. 😄

ok

Maybe someone could put this info on the WIki? Don't want to unilaterally change it. Thanks!

Regards,
Harris

ChakraCore for Windows Phone 8.1 Runtime application

Hi,

I am trying to use chakracore.dll in windows phone 8.1 runtime app. But I am getting System.DllNotFoundException: Unable to load DLL 'ChakraCore.dll': The specified module could not be found.
I am sure, I have placed chakracore.dll in my project. and buildAction : content, copyToOutputDirectory: copyAlways.

Please let me know chakracore.dll is tested against windows phone? If yes please provide sample.

Thanks in advance,
Pallam Madhukar

Access Violation

Could you please brief on how the issue #4 got resolved. We are facing a similar issue. There is access violation exception/ engine execution exception whenever there is a call on UI thread and succeding calls on the JS thread results in exception.

Bindings for C# like OpenGL C++ and some questions

Hi guys,

I want use the Chakra as an engine to process some scripts, something like using the node to process JS at runtime. I saw examples of OpenGL and is exactly what I need, but I need in C # would have some examples how this would be done in C #?

I have some doubts could they respond?

  • I wanted to use the chakra on a Web Service which would be the last to process JS, It would be interesting to keep pool of engine chakra?
  • You would have to reset it each call ? Or is indifferent created every time you have a new script?
  • I would have to do the 'binding' at runtime? like using the default import module ES6, I
    that if the import is something pure in JS works right? But what if you have to do "bindings" equal OpenGL I did not want to carry all at once.
  • EX: import Socket from './sockets.js'
    in folder ./ I would

Sockets.js (just javascript implementation)
Sockets.dll ( C# code, for bindings socket at chakra engine)

Sorry for poor English.
Thanks;

compiling failure in Windows

hi,

I got following errors while compiling the samples (in Windows 10):

chakracore.h(215): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
chakracore.h(215): error C2143: syntax error: missing ',' before '*'
chakracore.h(273): error C2061: syntax error: identifier 'uint16_t'

any ideas?

setTimeout example

Many JS libraries require setTimeout, and there are no good examples.

Memory management using the C# hosting sample

Hi,
I am developing a .NET scripting framework based on the hosting sample code from here: https://github.com/Microsoft/Chakra-Samples/tree/master/Chakra%20Samples/JSRT%20Win32%20Hosting%20Samples/Legacy%20JSRT%20Samples/C%23

When stress testing the framework I started experiencing AccessViolationExceptions in Javascript function calls. By investigating a bit, I realized that I had to call AddRef() on the JavaScriptValues passed as arguments to function calls, or else the ChakraCore garbage collector might collect the arguments before actually calling the function.
My solution currently looks something like this:

JavaScriptValue[] args = CreateArgs();
foreach ( var arg in args ) 
{
  arg.AddRef();
}
// call function here and release args when done

My questions are:

  • Is there still a race condition with the ChakraCore garbage collector between the CreateArgs method call and the arg.AddRef calls?
  • Will the code potentially try to call AddRef on a garbage collected argument?

From the documentation: https://msdn.microsoft.com/en-us/library/dn249552(v=vs.94).aspx

The main consideration is that the JavaScript garbage collector can only see references to values in two places: its runtime’s heap, and the stack. Thus, a reference to a JavaScript value that is stored inside of another JavaScript value or in a local variable on the stack will always be seen by the garbage collector. But references stored in other locations, such as heaps managed by the host or the system, will not be seen by the garbage collector and may result in premature collection of values that are still in use by the host.

Thanks in advance,

Morten

Can we create UI controls?

Hi,
I am new to chakra and going through the sample. I started with checking few Windows namespace properties like Windows.UI.Xaml.Window.current.height and it worked fine. So just to extend it a little further I thought to give a try to UI controls as below but ended up with exception "Object doesn't support this action". Can we not create UI controls?

function test()
{
var x=new Windows.UI.Xaml.Button();
return x;
}

test();

Canno't compile 'Hello World' example on MacOS

Hello,

I followed the instructions to compile ChakraCore on my Mac running ./build.sh --static --icu=/usr/local/opt/icu4c/include --test-build -j=2 --debug

I created the folder CrossPlatform inside ChakraCore repo and added sample.cpp and Makefile.

Then I built it running make BUILD_TYPE=Debug PLATFORM=darwin and here are the errors I get :

Undefined symbols for architecture x86_64:
  "icu_57::Normalizer2::getNFCInstance(UErrorCode&)", referenced from:
      PlatformAgnostic::UnicodeText::TranslateToICUNormalizer(PlatformAgnostic::UnicodeText::NormalizationForm) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::Normalizer2::getNFDInstance(UErrorCode&)", referenced from:
      PlatformAgnostic::UnicodeText::TranslateToICUNormalizer(PlatformAgnostic::UnicodeText::NormalizationForm) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::Normalizer2::getNFKCInstance(UErrorCode&)", referenced from:
      PlatformAgnostic::UnicodeText::TranslateToICUNormalizer(PlatformAgnostic::UnicodeText::NormalizationForm) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::Normalizer2::getNFKDInstance(UErrorCode&)", referenced from:
      PlatformAgnostic::UnicodeText::TranslateToICUNormalizer(PlatformAgnostic::UnicodeText::NormalizationForm) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::UnicodeString::UnicodeString(unsigned short const*, int)", referenced from:
      PlatformAgnostic::UnicodeText::NormalizeString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, unsigned int, char16_t*, int, PlatformAgnostic::UnicodeText::ApiError*) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
      PlatformAgnostic::UnicodeText::IsNormalizedString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::UnicodeString::~UnicodeString()", referenced from:
      PlatformAgnostic::UnicodeText::NormalizeString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, unsigned int, char16_t*, int, PlatformAgnostic::UnicodeText::ApiError*) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
      PlatformAgnostic::UnicodeText::IsNormalizedString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
      icu_57::Normalizer2::normalize(icu_57::UnicodeString const&, UErrorCode&) const in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "icu_57::UnicodeString::extract(unsigned short*, int, UErrorCode&) const", referenced from:
      PlatformAgnostic::UnicodeText::NormalizeString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, unsigned int, char16_t*, int, PlatformAgnostic::UnicodeText::ApiError*) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "vtable for icu_57::Replaceable", referenced from:
      icu_57::Replaceable::Replaceable() in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for icu_57::UnicodeString", referenced from:
      icu_57::UnicodeString::UnicodeString() in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for icu_57::UObject", referenced from:
      icu_57::UObject::UObject() in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "_u_charType_57", referenced from:
      PlatformAgnostic::UnicodeText::GetGeneralCategoryClass(unsigned int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
      PlatformAgnostic::UnicodeText::GetLegacyCharacterClassificationType(char16_t) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_errorName_57", referenced from:
      PlatformAgnostic::UnicodeText::TranslateToICUNormalizer(PlatformAgnostic::UnicodeText::NormalizationForm) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_hasBinaryProperty_57", referenced from:
      PlatformAgnostic::UnicodeText::IsIdContinue(unsigned int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_isIDStart_57", referenced from:
      PlatformAgnostic::UnicodeText::IsIdStart(unsigned int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_isUWhiteSpace_57", referenced from:
      PlatformAgnostic::UnicodeText::IsWhitespace(unsigned int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_strToLower_57", referenced from:
      PlatformAgnostic::UnicodeText::ChangeStringLinguisticCase(PlatformAgnostic::UnicodeText::CaseFlags, char16_t const*, unsigned int, char16_t*, unsigned int, PlatformAgnostic::UnicodeText::ApiError*) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_strToUpper_57", referenced from:
      PlatformAgnostic::UnicodeText::ChangeStringLinguisticCase(PlatformAgnostic::UnicodeText::CaseFlags, char16_t const*, unsigned int, char16_t*, unsigned int, PlatformAgnostic::UnicodeText::ApiError*) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
  "_u_strlen_57", referenced from:
      PlatformAgnostic::UnicodeText::IsNormalizedString(PlatformAgnostic::UnicodeText::NormalizationForm, char16_t const*, int) in libChakra.Jsrt.a(UnicodeText.ICU.cpp.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [testmake] Error 1

Any clue on what I missed ?

Example of calling ChakraCore from Spidermonkey using js-ctypes

In a similar vein to https://github.com/Microsoft/Chakra-Samples/tree/master/ChakraCore%20Samples/Hello%20World/Python I've put together an example that calls ChakraCore from Mozilla's JavaScript VM Spidermonkey using their builtin js-ctypes library. Code is here: https://gist.github.com/cosinusoidally/964164ea173d49ff700a6baeeea0ade6 (plus instructions on how to run the example code using one of Mozilla's prebuilt Spidermonkey shell binaries). As I mentioned in #34 I believe there are safety issues regarding JsValueRefs and the conservative stack scanning part of ChakraCore's garbage collector. In my example code I have addressed this issue by calling a C helper function that allocates variables on the C stack and then calls back in to Spidermonkey (which then uses the addresses of those stack allocated variables to hold the JsValueRefs).

Calling the example with:

js -e "unsafe=false;run_gc=true" example.js

should print the string "Hello world!" (generated by ChakraCore).

Calling the example with:

js -e "unsafe=true;run_gc=true" example.js

will segfault as unsafe=true causes the JsValueRefs to be allocated on the Spidermonkey heap (which then get collected when ChakraCore's JsCollectGarbage is called).

Using run_gc=true will cause JsCollectGarbage to be called at various points throughout the program. This simulates the worst case scenario where the GC happens to run when we are attempting to use JsValueRefs that have no reference on the C stack and a reference count of zero (ie JsValueRefs that are garbage).

If this is of interest I could work my example code into a pull requests.

Provide sample js script and command line input for ChakraCoreHost sample

When I am trying to run the ChakraCoreHost sample project, the instruction
5. Run the sample by pressing Ctrl+F5 or using Debug > Start Without Debugging.
is not correct.

After I stepped through the code, I got that I supposed to provide a path to a js file such as
C:\Users\XXX\Desktop\temp\runSimple.js

to exercise the host's function, I create runSimple.js with content:
host.runScript('C:/Users/XXX/Desktop/temp/simple.js');

Where simple.js has content:
host.echo("wbc",1,2,3);

Multiple js contexts

We have a requirement to run multiple js threads. I have created two js contexts on the same runtime. When trying to run on the second js context, there is an exception stating that the run time is active on another thread. Do I need to create a runtime for each js thread?

property access callback

A couple of queries:

  1. Is it possible to get callback whenever a property is accessed on an object even if the property is not defined on the object? This will help with lazy initialization and also with memory issues. The property accessed if valid, will be added as a property to the object in the c# code.
  2. Can the API "JsCreateExternalObject(
    In_opt void *data,
    In_opt JsFinalizeCallback finalizeCallback,
    Out JsValueRef *object
    );"
    hold a c# object as the "data"? Currently we are holding a int as data which maps to our c# object.

Need Chakra Sample for C#

Hi Team,

I am sorry for posting this as an issue. I am posting here because I don't have other option.

I am a C# developer, I read article about Chakra Engine which will be available to c# developers from Windows 10 development.
I am very excited to run JavaScript using C#. I am eagerly waiting to run my JavaScript applications in windows 10.

Please don't mine, I know I have posted it in wrong place, because I don't have other option to contact you.

Thanks,
Pallam Madhukar
Windows Developer.

Getting undefined when calling more than one function

I am trying to use the following javascript and I am getting an undefined error. Can you please suggest what am I doing wrong.

function a(){ return 10; }; function b(){ return 20; }; function c(){ return 30; }; function abc(){ return a()*b()*c(); }

CallFunction seems to require extra argument which is not documented.

I’m trying to use c# sample. I need to get the function from the script file and execute it with specific arguments. My script is

var f1= function foo(x, y) {
    return x + y;
}

My code is:

JavaScriptContext.RunScript(script);
var f1 = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("f1"));
var result = f1.CallFunction(JavaScriptValue.FromInt32(1), JavaScriptValue.FromInt32(2));

I expect code to return value of type number with value 3. It returns NaN instead.

I’ve spent quite a bit of time trying to understand this and it looks like CallFunction expects some additional argument. If I add any value (e.g. NULL as the first argument), everything works as expected.
Is this how it is supposed to work? What is the meaning of this extra argument?

Note addition of JavaScriptValue.Null

JavaScriptContext.RunScript(script);
var f1 = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("f1"));
var result = f1.CallFunction(JavaScriptValue.Null, JavaScriptValue.FromInt32(1), JavaScriptValue.FromInt32(2));

Throwing Exceptions

Could you please explain how to throw exception to the JS from C# code?

The js file goes something like this:
try
{
Button btn = new Button();//js object which refers to the ui Button control
btn.text = undefined;//this is expected to throw an exception
}
catch(e)
{

}

Inside the property callback for setter, I have tried the following:

public JavaScriptValue onSetPropertyNotificationFromChakra(JavaScriptValue callee, bool isConstructCall, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
{
try
{
//call to c# which throws the exception
}
catch(Exception ex)
{
//created an error object using the message from the exception
return JavaScriptValue.CreateError( ex.message);
}
}

I have tried returning the error object, and also throwing JavaScriptException but unable to hit the catch block in the JS code.

Feature Request: Increase C/C++ examples involving Properties.

I believe one of the samples needs an example on how to use the JsRT api ( functions available in ChakraCore.h ) to define object properties a little better. This involves a few common tasks that users might need when handling Scripts...

  • Define a Property as Constant from C/C++
  • Define a C/C++ Getter and Setter for an Object/Property.
  • Define Typed Arrays for use within ChakraCore using C/C++?
  • Define Typed Variables using C/C++ for use within ChakraCore? ( This is an ongoing proposal for ECMAScript base- see https://github.com/nikomatsakis/typed-objects-explainer)

host object creation with/without new operator

How to differentiate between an object that is created using "new" and the one without it? I have defined a host object and in the callback (JavaScriptNativeFunction ) for this object's creation, the value for the argument "bool isConstructCall" is always coming as "true" irrespective of the object being created with new or without it.

I want the object to be created only when it is created using the new operator.

Building HelloWorld on Linux, type "byte" is not defined

Building the Linux sample, while including the ChakraCore header file will complain about the type byte not being defined.

The workaround I found was to just define the type on top of sample.cpp before #include "ChakraCore.h" (The type can be defined as typedef unsigned char byte;)

Not really sure the best way to fix this permanently which is why I'm not posting the workaround as a PR. I noticed a todo in the source for ChakraCommon.h mentioning to reduce the usage of these types for better x-plat, I guess eventually that would fix this build issue?

Here is the compilation error I get on Ubuntu 16.04 --

juliusl@jlubuntu:~/Github/chakracore/crossplatform$ make BUILD_TYPE=Debug
g++ sample.cpp -Wall -lstdc++ -std=c++0x -I../lib/Jsrt -Wl,--whole-archive ../BuildLinux/Debug/lib/../pal/src/libChakra.Pal.a ../BuildLinux/Debug/lib/Common/Core/libChakra.Common.Core.a ../BuildLinux/Debug/lib/Jsrt/libChakra.Jsrt.a -Wl,--no-whole-archive -pthread -lm -ldl -licuuc -lunwind-x86_64 -Wno-c++11-compat-deprecated-writable-strings -Wno-deprecated-declarations -Wno-unknown-warning-option -o sample.o
In file included from ../lib/Jsrt/ChakraCore.h:26:0,
                 from sample.cpp:6:
../lib/Jsrt/ChakraDebug.h:692:137: error: ‘byte’ does not name a type
     typedef void (CHAKRA_CALLBACK *JsTTDInitializeForWriteLogStreamCallback)(_In_ size_t uriByteLength, _In_reads_(uriByteLength) const byte* uriBytes);
                                                                                                                                         ^
../lib/Jsrt/ChakraDebug.h:708:139: error: ‘byte’ does not name a type
     typedef JsTTDStreamHandle (CHAKRA_CALLBACK *TTDOpenResourceStreamCallback)(_In_ size_t uriByteLength, _In_reads_(uriByteLength) const byte* uriBytes, _In_z_ const char* asciiResourceName, _In_ b
                                                                                                                                           ^
../lib/Jsrt/ChakraDebug.h:719:120: error: ‘byte’ has not been declared
     typedef bool (CHAKRA_CALLBACK *JsTTDReadBytesFromStreamCallback)(_In_ JsTTDStreamHandle handle, _Out_writes_(size) byte* buff, _In_ size_t size, _Out_ size_t* readCount);
                                                                                                                        ^
../lib/Jsrt/ChakraDebug.h:730:123: error: ‘byte’ does not name a type
     typedef bool (CHAKRA_CALLBACK *JsTTDWriteBytesToStreamCallback)(_In_ JsTTDStreamHandle handle, _In_reads_(size) const byte* buff, _In_ size_t size, _Out_ size_t* writtenCount);
                                                                                                                           ^
../lib/Jsrt/ChakraDebug.h:763:44: error: ‘byte’ does not name a type
             _In_reads_(infoUriCount) const byte* infoUri,
                                            ^
../lib/Jsrt/ChakraDebug.h:787:44: error: ‘byte’ does not name a type
             _In_reads_(infoUriCount) const byte* infoUri,
                                            ^
../lib/Jsrt/ChakraDebug.h:935:18: error: ‘byte’ has not been declared
             _In_ byte* initialModPos);
                  ^
../lib/Jsrt/ChakraDebug.h:945:18: warning: ‘JsTTDRawBufferAsyncModifyComplete’ initialized and declared ‘extern’
             _In_ byte* finalModPos);
                  ^
../lib/Jsrt/ChakraDebug.h:945:18: error: ‘byte’ was not declared in this scope
../lib/Jsrt/ChakraDebug.h:945:24: error: ‘finalModPos’ was not declared in this scope
             _In_ byte* finalModPos);
                        ^
cc1plus: warning: unrecognized command line option ‘-Wno-unknown-warning-option’
cc1plus: warning: unrecognized command line option ‘-Wno-c++11-compat-deprecated-writable-strings’
Makefile:34: recipe for target 'testmake' failed
make: *** [testmake] Error 1

OpenGL Canvas sample in c#?

Is it possible to demonstrate the OpenGL sample in c#?

Eventually, my plan is to study that for making it works with UWP using Angle

Linux compile error

hi.

i can compile chakra in linux successfully.

but
when i tried compile helloworld sample in linux,
an error ocrrured below:

ChakraCommon.h:71:46: error: expected unqualified-id before string constant #define CHAKRA_API SET_API_VISIBILITY extern "C" JsErrorCode

i am compiling helloworld projects make file like bellow:
make BUILD_TYPE=Release

Using ChakraCore for win 10 UWP apps

I was exploring using ChakraCore instead of Chakra for UWP apps. I was doing it to leverage the new JsRT API to parse script as library(agarwal-sandeep/ChakraCore@83b1bcf?diff=unified) which was merged into ChakraCore. After having added the ChakraCore.dll to the project, there were exceptions stating that the below APIs were undefined.

  1. JsSetProjectionEnqueueCallback.
  2. JsProjectWinRTNamespace.
  3. JsStartDebugging.

Is it recommended to use ChakraCore for UWP apps in windows 10? Or should we wait for the features added in ChakraCore to be available on Chakra which I believe happens with OS update?

Also script debugging seems to be not working with ChakraCore!!!

Strict rules

Hi Limin,

When trying to set a property to a non-writable property and specifying "use strict" in the js code, we get an exception as expected. Is it possible to achieve this natively without writing "use strict" in the js code?

In JsSetProperty and JsDeleteProperty, there is an argument "bool useStrictRules". Is this related to "use strict"?

Regards,
Srinivas.

What are missing to get JsBridge support WebGl?

deltakosh/JsBridge#16

var ctx = document.createElement('canvas').getContext('experimental-webgl');

What needs to be done to make that works? There is no WebGLRenderingContext.cs
How to create WebGLRenderingContext.cs that links to the OpenGL example here?

    `public object getContext(string contextType)
    {
        if (contextType == "2d") {
            if (this.context == null) {
                this.context = new CanvasRenderingContext2D(this.window, this);
            }
            return this.context;
        }
       else if (contextType == "experimental-webgl" || contextType == "webgl")
        {
            if (this.context == null)
            {
                this.context = new WebGLRenderingContext(this.window, this);
            }
            return this.context;
        }
        return null;
    }`

Single runtime with multiple contexts - disposing context and avoiding memory leak

I am testing the chakra engine using the c# wrapper provided here. I have created a single runtime and I am then creating a new context for each script execution. (I have a requirement to run each script within a clean context). Unless I'm missing something, there doesn't seem to be a way to dispose of the context when I'm finished with it? As a result the process memory rockets up with each script invocation. At the moment I'm working around this by creating (and then disposing of) a new runtime for each script call but I imagine this creates an unnecessary (and probably quite heavy) performance overhead. It does however clean up memory!

Thanks,
Stuart

'Runtime is active on another thread' error with Chakra and WebView control combination

I have a UWP app and a page with a WebView control.

The WebView points to a version of the Monaco Editor (https://github.com/Microsoft/monaco-editor) embedded in my app:

WebViewEditor.Navigate(new Uri("ms-appx-web:///Monaco/index.html"));

All works well.

However if I then try to use the Chakra engine, I immediately get 'wrong thread' exceptions.

The following will fail on the second line attempting to create a new context:

var runtime = JavaScriptRuntime.Create();
var context = runtime.CreateContext();

If I remove the WebView navigation above, the chakra engine functions fine.

I wouldn't have expected there to be any interaction? I would have expected a new chakra runtime to operate in isolation and have no threading issues when used in combination with a WebView control. Very odd. Any ideas?

Thanks,
Stuart

Need the update to RTM version(10240)

After Modifing the csproj file to "10.0.10240.0 ", and then compile the project, it showes:

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Diagnostics.Tracing.EventSource.Redist.1.1.16-beta\build\portable-net45+win8+wpa81\Microsoft.Diagnostics.Tracing.EventSource.Redist.targets. JsRT_UWP_Sample D:\Source\Repos\Chakra-Samples\JavaScript Runtime Samples\JSRT Universal Windows Apps Hosting Samples\C#\JsRT_UWP_Sample\JsRT_UWP_Sample.csproj 165

JSON.stringify() and toString()

  1. When using toString() on a host object, I am getting the value "[object [object Object]]" instead of [object Button]. (where Button is my host object). How to achieve this?
  2. When calling JSON.stringify(obj), I am getting the value as "{}" without any of the values of the properties that have been defined on this host object. Only the properties that have been set with values on the object are showing. Properties which have been set using "defineProperty" are not showing up. How can we get all the values of the defined properties in the JSON string.

Passing object to runtime component

  1. While trying to pass an object to the projected runtime component, I am getting an error saying "type mismatch. The sample is uploaded @ https://onedrive.live.com/redir?resid=9C4512A9CBBBEB98!114&authkey=!AMRXOrhTk2Ojq6Q&ithint=file%2czip . How do I pass the object which can be accepted in the runtime component as a dictionary?
  2. Even when returning a dictionary from the runtime Component ("getMap2"), it is returning as "System.Collections.Generic.Dictionary`2[System.String,System.Int32]" and not as [object Object].

Is this expected behavior? Please click on the "Execute" button to execute the script in the file "script11.js".

Run a JS function from existing context?

(C#/UWP)

I would like to:

  1. Run a JS script that exports a function
  2. Run that function later on, on-demand

For 1. I just use ChakraCore.runScript(..). For 2. I wrote this ChakraCore.callFunction(..):

        public string callFunction(string function, string[] arguments)
        {
            IntPtr returnValue;

            try
            {
                // Get function id
                JavaScriptValue global;
                Native.JsGetGlobalObject(out global);
                JavaScriptPropertyId id;
                if (Native.JsGetPropertyIdFromName(function, out id) != JavaScriptErrorCode.NoError)
                    return "couldn't get property id.";
                // Is this the same as global.GetProperty(id)?
                JavaScriptValue jsFunc;
                Native.JsGetProperty(global, id, out jsFunc);

                // convert args
                JavaScriptValue[] jsArguments = new JavaScriptValue[arguments.Length+1];
                jsArguments[0] = global;
                int i = 1;
                foreach (string arg in arguments) {
                    JavaScriptValue jsArg;
                    UIntPtr length = new UIntPtr((uint) arg.Length);
                    Native.JsPointerToString(arg, length, out jsArg);
                    jsArguments[i] = jsArg;
                    i += 1;
                }

                //
                JavaScriptValue result;
                JavaScriptErrorCode err = Native.JsCallFunction(
                    jsFunc, jsArguments, (ushort) jsArguments.Length, out result);
                if (err != JavaScriptErrorCode.NoError)
                    return "couldn't execute function: " + err.ToString() + ".";

                // 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);
        }

This fails with "couldn't execute function: InvalidArgument". Please advise, JsRT documentation is (afaict) lackluster.

JS Debugging

When trying to debug the js code, upon expanding the tool tip for "prototype" of an object, the application is terminating as in the attached image. There are forty to fifty properties defined on the object's prototype which in turn trigger the getter callback and gather the info from c# code. However, each of the properties is accessible when accessed individually. Is this expected? If so, it would have been convinient if prototype did not show up as the application terminates if prototype is expanded accidentally.
apptermination

How to pass .Net object to Javascript context

Hi,

I just started a project what is to embed Chakracore into .Net application.

The main goal of application is to run realtime hosting. The application is to get javascript code from client side and process external objects with it.

The external object is supposed to be complicated .NET type.

But I have some difficulties in passing the external object into javascript context.

I tired below code and ran javascript code to see the test object exists.

But the result showed the object exits but no property for the object at all even thou the test object had data members.

JavaScriptValue global = JavaScriptValue.GlobalObject;

Test test = new Test();
GCHandle handle = GCHandle.Alloc(test);
IntPtr ptr = (IntPtr)handle;

JavaScriptValue jsv = JavaScriptValue.CreateExternalObject(ptr, null);
JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString("test");
global.SetProperty(propertyId, jsv, false);

Can anyone tell me how to implement this or give me any good example?

Thanks,

Callback when function object is garbage collected.

Let us say I have a function object in JS.
function myFunction(){}
I am assuming that by assigning to null in javascript code, it could be made available for garbage collection.
myFunction = null;

Is there a way to receive a callback notifying that a function object is being collected just like we have for external objects (JsCreateExternalObject)?

[JsCreateExternalArrayBuffer] in native.cs returns bool, should be JavaScriptValue

Native.cs

internal static extern JavaScriptErrorCode JsCreateExternalArrayBuffer(IntPtr data, uint byteLength, JavaScriptObjectFinalizeCallback finalizeCallback, IntPtr callbackState, out bool result);

Document

STDAPI_(JsErrorCode) JsCreateExternalArrayBuffer(
  _Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data,
  _In_ unsigned int byteLength,
  _In_opt_ JsFinalizeCallback finalizeCallback,
  _In_opt_ void *callbackState,
  _Out_ JsValueRef *result
);

JavaScriptProjectionEnqueueCallback

I am getting an error when trying to use "JsSetProjectionEnqueueCallback". Please find the sample app @ https://onedrive.live.com/redir?resid=9C4512A9CBBBEB98!111&authkey=!ALhEoAFR-tPVGC4&ithint=file%2czip

I am trying to execute the following script:
var uri = new Windows.Foundation.Uri("http://google.com");
var httpClient = new Windows.Web.Http.HttpClient();

httpClient.getStringAsync(uri).done(function () {
// do something with the string content "
Debug.writeln("finished");
}, onError);
function onError(reason) {
// error handling
Debug.writeln( "onError");
}

Could you please help me with this?

Access violation exception

Hi,

Sorry if it's not the right place to ask but wasn't sure how else to contact about this. Currently working on a UWP C# app that uses JsRT. Got an intermittent issue where a SystemAccessViolationException occurs about reading/writing protected memory when invoking the JsCallFunction method. Any suggestions on how this can happen and how to fix it?

In case it helps, we're using MVVM cross and use the messenger plugin to subscribe for messages on the main thread. When a message is received , then we make a call to the JsCallFunction method. The first argument (which i'm told represents "this"), is an object returned by a javascript function similar to the following

function createFoo(){
return new Foo();
}

Initially I thought it's because we had to pin the object so it doesn't get garbage collected via JsAddRef but doing so or even create a property on the global object to store that instance of the Foo class didn't help either. Would appreciate it if you could provide some guidance on the diagnosing this issue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.