I'm looking for an "inline" way to run native Swift code from Javascript strings. At the moment, what I do is as follows:
I've extracted the JSContext from my web view, so I have direct access to my javascript environment:
var jsContext = myWebView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as JSContext
Once I have my context, I'm setting a new object in it to call my code block:
var codeClosure: @objc_block ()->() = { ()->() in println("this is my swift code closure") }
var casted: AnyObject = unsafeBitCast(codeClosure, AnyObject.self) as AnyObject
jsContext.setObject(casted, forKeyedSubscript: "callMySwiftClosure")
Which enables me to call my code as it's a regular javascript function:
myWebView.stringByEvaluatingJavaScriptFromString("callMySwiftClosure()")
That's pretty simple, and works very well.
Now, I'm trying to figure out how can I "inject" the swift closure directly into a javascript string, without explicitly creating a new object in the JSContext. Meaning, I'd like to be able to do something like that:
myWebView.stringByEvaluatingJavaScriptFromString("\(codeClosure)")
Any ideas on how to do that?