microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

Call function from host when script is a module? #467

Closed dementcore closed 1 year ago

dementcore commented 1 year ago

Hi again @ClearScriptLib and sorry for inconveniences!!

When a script is evaluated or executed as a module. How can i call a script method from host code?

Example code:

            var a = engine.Evaluate(new DocumentInfo { Category = ModuleCategory.Standard },@"
                    export default async function main()
                    {
                        await someFunc();
                    }
            "); //a is undefined

            engine.Script.main(); //this not works, throws method not found

Note: I need that the script be a module because it's needed to import another modules in it, so evaluate as a regular script is not possible for the requeriments i have.

Thanks!

Best regards

ClearScriptLib commented 1 year ago

Hi @dementcore,

Module exports are only accessible via the import mechanism. However, a module can add properties to globalThis:

engine.AddHostType(typeof(Console));
engine.Execute(new DocumentInfo { Category = ModuleCategory.Standard }, @"
    globalThis.main = function () {
        Console.WriteLine('Hello, world!');
    }
");
engine.Script.main();

Good luck!

dementcore commented 1 year ago

Thank you very much! Works like a charm!

Regards