之前一直没有使用过JSContext,昨天遇到相关问题就试了一下。
- 加载本地HTML文件
NSString *mainBundle = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:mainBundle];
NSString *htmlPath = [NSString stringWithFormat:@"%@/test.html", mainBundle];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
[self.webview loadHTMLString:htmlString baseURL:baseURL];
self.webview.delegate = self;`
- JSContext调用
self.context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
[self.context evaluateScript: @"var sayHello;$(document).ready(function() { sayHello=function(name){ return 'Hello, ' + name; }});"];
JSValue *function = self.context[@"sayHello"];
JSValue* result = [function callWithArguments:@[@"world"]];
NSString *re = [result toString];
NSLog(@"%@", re);`
-
输出结果
Paste_Image.png - 遇到问题:
- 无法加载本地 JS 文件,搜索了一下,应该使用http://stackoverflow.com/questions/17252073/ios-open-uiwebview-with-local-javascript-files 里提到的方法。
- demo 中发现只能通过 html 中加载 jQuery 的方式成功调用 sayHello 方法。尝试使用http://stackoverflow.com/questions/23397658/how-to-include-a-external-library-in-javascriptcore 里的方法,成功加载jQuery文件,但是 sayHello 方法无法调用成功。
- 如果将 JS 部分修改为下面的写法,在 JSContext 也是取不到
function 的,怀疑是 $ 符号无法在 JSContext 中使用。求大牛解答。
$(document).ready(function() {
$.fn.helloWorld = function(name) {
var result = "hello,"+name;
return result;
};
});