方法/步骤
方法一:
通过webview的delegate方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
在上面这个函数中,通过截取NSURLRequest解析js中传递过来的参数,和网址再根据参数来调用已定义好的方法。
但现在我们介绍另外一种方法。
方法二:我们用 javascriptCore.framework 这个库。
首先在建立一个UIWebView,代码如下:
#import "webview.h"
#import
@implementation webview
-(id)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
if( self ){
self.webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 310, self.bounds.size.width, 300)];
self.webview.backgroundColor=[UIColor lightGrayColor];
NSString *htmlPath=[[NSBundle mainBundle] resourcePath];
htmlPath=[htmlPath stringByAppendingPathComponent:@"html/index.html"];
NSURL *localURL=[[NSURL alloc]initFileURLWithPath:htmlPath];
[self.webview loadRequest:[NSURLRequest requestWithURL:localURL]];
[self addSubview:self.webview];
JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"log"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
NSLog(@"this: %@",this);
NSLog(@"-------End Log-------");
};
}
return self;
}
@end
在上面代码中,我们先引入了javascriptCore.framework这个库,然后webview那一套就不多说了,注意我加载一个静态网页。然后我用
JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
获取该UIWebview的javascript执行环境。
在该javascript执行环境中,定义一个js函数,注意关键点来了,这个函数的执行体完全是 objective-c代码写的,也就是下面:
context[@"jakilllog"] = ^() {
NSLog(@"Begin Log");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
NSLog(@"-------End Log-------");
};
oc端已经写好了,我们现在进行html部分。
看看UIWebView 中所加载的 html及其js代码是如何写的。