Skip to content

Instantly share code, notes, and snippets.

@alastaircoote
Last active December 31, 2015 23:09
Show Gist options
  • Save alastaircoote/8058425 to your computer and use it in GitHub Desktop.
Save alastaircoote/8058425 to your computer and use it in GitHub Desktop.
Using iOS's JavascriptCore as a Web Worker of sorts
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.JavaScriptCore;
namespace jscoretest
{
public partial class jscore_testViewController : UIViewController
{
public jscore_testViewController () : base ("jscore_testViewController", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
var webV = new UIWebView (new RectangleF (0, 0, 320, 480));
base.Add (webV);
var pageHtml = @"
<a href='#test'>test</a>
<script>
window.receiveMsg = function(msg) {
alert(msg);
};
</script>
";
var jsScript = @"
var testFunc = function(){
return 'hello, this is a test message';
}
";
JSContext context = new JSContext ();
context.EvaluateScript (jsScript);
webV.LoadHtmlString (pageHtml, new NSUrl("http://localhost"));
// This is what we're using to send events from the page back to iOS. The page changes the page fragment
// to pass events and potentially data
webV.ShouldStartLoad = (delegate(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
if (request.Url.Fragment == "test") {
var result = context.EvaluateScript ("testFunc()");
webV.EvaluateJavascript("window.receiveMsg('" + result.ToString() + "');");
return false;
}
return true;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment