在UIWebView中,代码如下:
- //
- // webview.m
- // login
- //
- //
- // SWWebBrowser.m Create by William Sterling on 14-1-20.
- //
- #import "webview.h"
- #import <JavaScriptCore/JavaScriptCore.h>/*导入库*/
- @implementation webview
- -(id)initWithFrame:(CGRect)frame
- {
- self=[super initWithFrame:frame];
- if( self ){
- self.webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 320, 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"] = ^() {
- dlog(@"+++++++Begin Log+++++++");
- NSArray *args = [JSContext currentArguments];
- for (JSValue *jsVal in args) {
- dlog(@"%@", jsVal);
- }
- JSValue *this = [JSContext currentThis];
- dlog(@"this: %@",this);
- dlog(@"-------End Log-------");
- };
- // [context evaluateScript:@"log('ider', [7, 21], { hello:'world', js:100 });"];
- }
- return self;
- }
- @end
注释:
JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
获取该UIWebview的javascript执行环境。
(2)index.html代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <meta name="description" content="">
- <meta name="viewport" content="width=device-width; initial-scale=1.0">
- <script type="text/javascript" src="index.js"></script>
- </head>
- <button id="hallo" onclick="buttonClick()"> 点击button</button>
- </body>
- </html>
- function buttonClick()
- {
- log("hello world");
- }
意思是点击这个button,就调用jakilllog()函数,jakilllog()函数显然是我们在oc中实现的一个block段,
就是上述绿色部分的block段。
点击button会执行么?答案是肯定的。