美文网首页
UIWebView中使用JSContext调用jQuery中的方

UIWebView中使用JSContext调用jQuery中的方

作者: savizz | 来源:发表于2017-01-14 13:58 被阅读0次

之前一直没有使用过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);`
$(document).ready(function() {
    $.fn.helloWorld = function(name) {
      var result = "hello,"+name;
      return result;
    };
});

相关文章

网友评论

      本文标题:UIWebView中使用JSContext调用jQuery中的方

      本文链接:https://www.haomeiwen.com/subject/jfpebttx.html