Chakracore: Run a specified function in js file using ChakraCore?

Created on 12 Jan 2017  路  6Comments  路  Source: chakra-core/ChakraCore

If my scripts in js file. how do I run a specified function in this js file.please give me the code ,thank a lot.

Question

All 6 comments

Hi @luxiao6620217 - can you provide more details? Are you trying to run your js file inside of Edge?

Hi, @dilijev @digitalinfinity . For example, the script in js file(many functions in this file) is:
function processLine(line) {
return line.trim()
.replace(/[<>&"'\u0000-\u001F\u007E-\uFFFF]/g, function(x) {
return '&#' + x.charCodeAt(0) + ';'
})
.replace(/*(.*?)*/g, function(x, m) {
return '' + m + '';
};
}
In c++ project(windows system), I want to add the script in the engine, and run the function 'processLine' with parameter 'line'. At last, I need to get the return from the engine. just like 'MSScriptControl' of COM msscript.ocx.
Thank you!

Maybe you could load the script and then run a new script with a call to that function, and process the result that way.

@liminzhu do you have any suggestions?

@luxiao6620217 you can use the JSRT APIs in ChakraCore to achieve your goal. Here is a sample Hello World application that you can use to get started. Once you load your script using either JsRunScript, you can try something like the following order of operations:

  1. Call JsGetGlobalObject to get the global object
  2. Get the PropertyIdRef for "processLine" by calling JsGetPropertyIdFromName
  3. Get the JsValueRef corresponding to processLine by calling JsGetProperty, passing in the global object from step 1 and the PropertyIdRef from step 2.
  4. Get a JsValueRef corresponding to line by calling JsCreateString, passing in the value of line
  5. Call JsCallFunction with the function object retrieved in step 2, and with the parameter set to the string created in step 4.
  6. Call JsStringToPointer to get the result of processLine as a wchar_t pointer in C++

Documentation for the JSRT API is here and you can study about the basic ideas in JSRT here.

Hope that helps. Feel free to let us know if you need any more help!

@digitalinfinity good answer, thank you for your help. It is very useful for me.

Closing as the question seems to be addressed already.

Was this page helpful?
0 / 5 - 0 ratings