Taritsyn/JavaScriptEngineSwitcher

Extend JavaScript library with global functions

CzaiStefanB opened this issue · 7 comments

First let me thank you for that really nice library.

I have one qustion. Is it possible to extend the JavaScript library with global functions (IActiveScript::AddNamedItem with dwFlags set to SCRIPTITEM_GLOBALMEMBERS). I can imagine something like IJsEngine.EmbedHostType(string itemName, Type type, ScriptItem.GlobalMembers) or IJsEngine.EmbedHostObject(string itemName, object value, ScriptItem.GlobalMembers). I did not find a way to do that or did I overlook something?

Thanks!

Hello!

You can give an example of code that requires this functionality.

I think that in the context of this library this cannot be done.

The main principle of the JavaScript Engine Switcher is as follows:

JavaScript Engine Switcher determines unified interface for access to the basic features of popular JavaScript engines (…). This library allows you to quickly and easily switch to using of another JavaScript engine.

Perhaps newer script engines like Chakra doesn't support that function any longer so you will not be able to add that to the common interface. In that case I will go with the EmbedHostType approach.

This approach is not supported by all other engines.

Already now you can use the following approach:

using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
{
    var getModuleResult = (Func<string, string>)StaticClassName.GetModuleResult;

    engine.EmbedHostObject("GetModuleResult", getModuleResult);
    string result = engine.Evaluate<string>("GetModuleResult('Module1')");

    Console.WriteLine(result);
}

I was not aware that this possibility exists. I will use that approach. Thank you for your help.

This is not even a JavaScript Engine Switcher feature, but a. NET feature. We just convert the method call to a delegate.