JSContext Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Encapsulates a JavaScript engine.
[Foundation.Register("JSContext", true)]
public class JSContext : Foundation.NSObject
[<Foundation.Register("JSContext", true)>]
type JSContext = class
inherit NSObject
- Inheritance
- Attributes
Remarks
The JSContext is the central object of the JavaScriptCore namespace. The JSContext maintains a JavaScript environment (manipulated by the Item[NSObject] property) and evaluates scripts with the EvaluateScript(String, NSUrl) method.
Application developers will often want to assign a delegate to the ExceptionHandler property to gain access, in their Xamarin.iOS code, of exceptions raised in the JavaScript realm.
The following example shows the basic use of JSContext. The context is instantiated and a simple exception handler is assigned. One of the From(NSObject, JSContext) method overloads is used to assign values to the JavaScript variables arg1 and arg2. The EvaluateScript(String, NSUrl) method evaluates the JavaScript and returns the result, which is converted back into a .NET object with the ToInt32() method.
jsContext = new JSContext();
jsContext.ExceptionHandler = (context, exception) => {
Console.WriteLine(exception);
};
jsContext[new NSString("arg1")] = JSValue.From(2, jsContext);
jsContext[new NSString("arg2")] = JSValue.From(2, jsContext);
var jsResult = jsContext.EvaluateScript("arg1 + arg2;");
var four = jsResult.ToInt32();
The JSContext contains the global JavaScript context, including variables set by JavaScript calculations, as shown in the following example:
jsContext.EvaluateScript("sum = 2 + 2;");
var four = jsContext[(NSString)"sum"].ToInt32();
Calling C# code from JavaScript
Developers can extend the IJSExport interface to define methods that can be called from JavaScript. Developers must mark that interface with the ProtocolAttribute attribute and must mark JavaScript-callable methods with the ExportAttribute attribute. They must also set the MSBuild property Registrar to "static" or "managed-static" in the project files. For example:
[Protocol ()]
interface IMyJSVisibleProtocol : IJSExport {
[Export ("myFunc")]
int MyFunc ();
[Export ("Arity2:With:")]
NSObject Arity2With(NSObject arg1, NSObject arg2);
}
class MyJSExporter : NSObject, IMyJSVisibleProtocol
{
public int MyFunc ()
{
Console.WriteLine ("Called!");
return 42;
}
public NSObject Arity2With(NSObject arg1, NSObject arg2)
{
Console.WriteLine ("Arity 2 function called with " + arg1 + " " + arg2);
return (NSNumber) 42;
}
}
The above example:
- Defines
IMyJSVisibleProtocolas extending IJSExport;: - Decorates
IMyJSVisibleProtocoland it's methodMyFuncwith the ProtocolAttribute and ExportAttribute attributes;: - Implements the interface:
To expose the IMyJSVisibleProtocol to JavaScript, the developer could use code like the following in the ViewDidLoad() method of their UIViewController:
webView = new UIWebView(UIScreen.MainScreen.Bounds);
var context = (JSContext) webView.ValueForKeyPath ((NSString) "documentView.webView.mainFrame.javaScriptContext");
context.ExceptionHandler = (JSContext context2, JSValue exception) =>
{
Console.WriteLine ("JS exception: {0}", exception);
};
var myExporter = new MyJSExporter ();
context [(NSString) "myCSharpObject"] = JSValue.From (myExporter, context);
webView.LoadRequest(NSUrlRequest.FromUrl(new NSUrl("MyHtmlFile.html", false)));
The above C# code:
- Creates a UIWebView which will be displayed to the end user;:
- Gets the JSContext of the UIWebView object's main frame;:
- Adds an exception handler so that JavaScript trouble will be visible to the Xamarin project;:
- Instantiates a new
MyJSExporterobject that, as described above, implements theIMyJSVisibleProtocol;: - Adds that object to the JSContext with the name
myCSharpObject;: - Loads an HTML file (see below):
Finally, the HTML file that is loaded into the UIWebView and into whose JSContext the MyJSExporter object has been placed can access the object from within JavaScript:
<html>
<head>
<title></title>
<script type="text/javascript">
function callXamObject() {
// `myCSharpObject` injected into JS context by C# code `context [(NSString) "myCSharpObject"] = JSValue.From (...etc...`
var resultCalculatedInCSharp = myCSharpObject.myFunc();
document.getElementById("Output").innerHTML = resultCalculatedInCSharp;
}
function callArity2Method() {
//Note how this is mapped by [Export ("Arity2:With:")]
var result = myCSharpObject.Arity2With("foo", "bar");
}
</script>
</head>
<body>
<div onclick="callXamObject()" class="button">
Click Me
</div>
<div id="Output">Value</div>
</body>
</html>
In order to export a C# object so that it is visible to JavaScript, the developer must add the --registrar:static argument to the arguments used by mtouch. In Xamarin Studio, this is done in the Project Options dialog, in the Build Options / iOS Build pane:

Another technique for calling C# code from Xamarin.iOS is to use REST, as shown in the following:
In the JavaScript code, use XMLHttpRequest and standard JSON techniques to post and parse a query to a REST service running on the local device:
<html>
<head>
<title></title>
<script type="text/javascript">
function callCSharp(msg) {
var request = new XMLHttpRequest();
request.open('GET','http://127.0.0.1:1711/', false);
request.send();
if(request.status == 200){
alert(JSON.parse(request.responseText));
}else{
alert("Error");
}
}
</script>
</head>
<body>
<div onclick="callCSharp('this is a test')" class="button">
Click Me
</div>
</body>
</html>
In the application, use HttpListener to listen and respond to that request:
//Wire up listener
listener = new HttpListener();
listener.Prefixes.Add("http://*:1711/");
listener.Start();
listener.BeginGetContext(new AsyncCallback(Callback), listener);
//....etc...
void Callback(IAsyncResult result)
{
//Get the listener context
var context = listener.EndGetContext(result);
//Start listening for the next request
listener.BeginGetContext(new AsyncCallback(Callback), listener);
var response = CalculateResponse();
var responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
context.Response.ContentType = "text/json";
context.Response.StatusCode = HttpStatusCode.OK;
context.Response.ContentLength64 = responseBytes.Length;
context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
context.Response.OutputStream.Close();
}
Finally, a third technique is to poll the JSContext for a flag set by a JavaScript calculation.
Constructors
| Name | Description |
|---|---|
| JSContext() | |
| JSContext(JSVirtualMachine) | |
| JSContext(NativeHandle) |
A constructor used when creating managed representations of unmanaged objects. Called by the runtime. |
| JSContext(NSObjectFlag) |
Constructor to call on derived classes to skip initialization and merely allocate the object. |