Sample code for 30+ languages & platforms
PureBasic

Call a JavaScript Function Returning a String

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a string.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJs.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

    ; This is the JavaScript function we'll call:

    ; function greet(name) {
    ;     return "Hello, " + name + "!";
    ; }

    sbScript.i = CkStringBuilder::ckCreate()
    If sbScript.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbScript,"function greet(name) { return " + Chr(34) + "Hello, " + Chr(34) + " + name + " + Chr(34) + "!" + Chr(34) + "; }")

    js.i = CkJs::ckCreate()
    If js.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    result.i = CkJsonObject::ckCreate()
    If result.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkEmitCompact(result, 0)

    ; Call Eval to add the function to the context's global object
    success = CkJs::ckEval(js,sbScript,result)
    If success = 0
        ; Examine the result for an exception.
        Debug CkJsonObject::ckEmit(result)

        ; Also examine the LastErrorText.
        Debug CkJs::ckLastErrorText(js)
        CkStringBuilder::ckDispose(sbScript)
        CkJs::ckDispose(js)
        CkJsonObject::ckDispose(result)
        ProcedureReturn
    EndIf

    ; ------------------------------------------------------------------------------
    ; Call the function greet("Michael")

    funcCall.i = CkJsonObject::ckCreate()
    If funcCall.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Create JSON specifying the function name and arguments

    ; {
    ;   "name": "greet",
    ;   "args": [ "Michael" ]
    ; }

    CkJsonObject::ckUpdateString(funcCall,"name","greet")
    CkJsonObject::ckUpdateString(funcCall,"args[0]","Michael")

    success = CkJs::ckCallFunction(js,funcCall,result)
    If success = 0
        ; Examine the result for an exception.
        Debug CkJsonObject::ckEmit(result)

        ; Also examine the LastErrorText.
        Debug CkJs::ckLastErrorText(js)
        CkStringBuilder::ckDispose(sbScript)
        CkJs::ckDispose(js)
        CkJsonObject::ckDispose(result)
        CkJsonObject::ckDispose(funcCall)
        ProcedureReturn
    EndIf

    Debug CkJsonObject::ckEmit(result)

    ; Output:
    ; {
    ;   "type": "string",
    ;   "value": "Hello, Michael!"
    ; }

    retval.s = CkJsonObject::ckStringOf(result,"value")
    Debug retval

    ; Output:
    ; Hello, Michael!


    CkStringBuilder::ckDispose(sbScript)
    CkJs::ckDispose(js)
    CkJsonObject::ckDispose(result)
    CkJsonObject::ckDispose(funcCall)


    ProcedureReturn
EndProcedure