#
Calling JavaScript
h5 provides several mechanisms to interact with existing JavaScript code and libraries.
#
Using Script.Write and Script.Eval
The most direct way to call JavaScript is by using Script.Write or Script.Eval from the H5 namespace.
#
Script.Write
Script.Write injects raw JavaScript code directly into the compiled output.
using H5;
public void SayHello()
{
// Emits: alert("Hello from JavaScript!");
Script.Write("alert('Hello from JavaScript!');");
}
You can also use placeholders for arguments:
public void LogMessage(string message)
{
// Emits: console.log(message);
Script.Write("console.log({0});", message);
}
#
Script.Eval
Script.Eval evaluates a JavaScript expression at runtime and returns the result.
public int Add(int a, int b)
{
// Evaluates: a + b
return Script.Eval<int>($"{a} + {b}");
}
#
Using Script.Call, Script.Get, Script.Set
Helper methods are available to interact with JavaScript objects and functions dynamically.
using H5;
// Call a global function
Script.Call("myFunction", "arg1", 123);
// Get a global variable
var title = Script.Get<string>("document.title");
// Set a global variable
Script.Set("window.myVar", "value");
#
Integrating External Code
For a more type-safe approach, you can define external interfaces using the [External] attribute.
#
[External] Attribute
Use [External] to define C# bindings for existing JavaScript libraries. The compiler will not generate implementation code for these types but will assume they exist at runtime.
[External]
[Name("Math")]
public static class Math
{
[Name("random")]
public static extern double Random();
[Name("max")]
public static extern double Max(double a, double b);
}
// Usage
double r = Math.Random();
#
[Template] Attribute
The [Template] attribute allows you to specify exactly how a method call should be translated to JavaScript. This is powerful for adapting C# method signatures to JavaScript APIs.
[External]
public static class Console
{
[Template("console.log({0})")]
public static extern void Log(object message);
[Template("console.warn({0}, {1})")]
public static extern void Warn(string category, string message);
}
When you call Console.Log("Hello"), h5 generates console.log("Hello").
#
[Script] Attribute
The [Script] attribute allows you to inject a script block directly into the generated code for a method.
public class MyClass
{
[Script("alert('Hello from inline script!');")]
public void InlineScript()
{
}
}
This is similar to Script.Write but declarative.