|
| 1 | +## JavaScript Interop |
| 2 | + |
| 3 | +Usually, to interact with JavaScript, we need to either execute some code from C# on the JavaScript side or get value(s) from the JavaScript side in C#. |
| 4 | + |
| 5 | +### How to execute JavaScript code from C#? |
| 6 | + |
| 7 | +First of all, any JavaScript code performed inside window scope, which mean we need to know window. |
| 8 | +After it we can write code as follow: |
| 9 | +```csharp |
| 10 | +// our window pointer |
| 11 | +var windowPointer = ...; |
| 12 | +// script that will be performed in window scope |
| 13 | +var script = '2 + 3'; |
| 14 | + |
| 15 | +SciterValue result; |
| 16 | + |
| 17 | +// evaluate |
| 18 | +Host.ExecuteWindowEval(windowPointer, script, out result); |
| 19 | + |
| 20 | +var calculatedValue = Host.GetValueInt32(ref result); |
| 21 | + |
| 22 | +Console.WriteLine("Result is " + calculatedValue); |
| 23 | +``` |
| 24 | + |
| 25 | +### How to execute C# code from JavaScript? |
| 26 | + |
| 27 | +With EventHandler we can handle a lot of changes to an element, but what if we want to literally call C# methods from JavaScript? |
| 28 | +We can do this, but it will look like we are handling an event from the element. |
| 29 | + |
| 30 | +First of all we need to markup as follow: |
| 31 | +```html |
| 32 | +... |
| 33 | +<!-- we define some element in HTML and attach our behaviour --> |
| 34 | +<div id="myid" style="behavior: mybehaviour"></div> |
| 35 | +... |
| 36 | +<script> |
| 37 | +const element = document.getElementById('myid'); |
| 38 | +const result = element.xcall("csharpmethod", "string1", 1); |
| 39 | +console.log(result); |
| 40 | +</script> |
| 41 | +``` |
| 42 | + |
| 43 | +Second we need to handle call in C# and to do something: |
| 44 | +```csharp |
| 45 | +public class MyHandler : ElementEventHandler { |
| 46 | + |
| 47 | + public MyHandler ( nint element, SciterAPIHost host ) : base ( element, host ) {} |
| 48 | + |
| 49 | + public override (SciterValue? value, bool handled) ScriptMethodCall ( string name, IEnumerable<SciterValue> arguments ) { |
| 50 | + // only if called csharpmethod |
| 51 | + if ( name == "csharpmethod" ) { |
| 52 | + // read first string parameter |
| 53 | + var stringParameter = arguments.ElementAt ( 0 ); |
| 54 | + var stringValue = Host.GetValueString(ref stringParameter); |
| 55 | + // read second number parameter |
| 56 | + var intParameter = arguments.ElementAt ( 1 ); |
| 57 | + var intValue = Host.GetValueInt32(ref intParameter); |
| 58 | + // create result value |
| 59 | + return (Host.CreateValue(stringValue + intValue), true); |
| 60 | + } |
| 61 | + |
| 62 | + return (null, false); |
| 63 | + } |
| 64 | +``` |
0 commit comments