JSContext、webView

加载webView
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
webView.delegate = self;
// NSString *path = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
// NSURL *url = [NSURL URLWithString:path];
// NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
// [webView loadRequest:request];
[webView loadHTMLString:html baseURL:nil];
修改Element
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//查询标签
NSString *str = @"var word = document.getElementById('word');"
@"alert(word.innerHTML)";
[webView stringByEvaluatingJavaScriptFromString:str];
//为网页添加标签
NSString *addStr = @"var img = document.createElement('img');"
@"img.src = 'logo.png';"
@"img.width = 300;"
@"img.heigth = 100;"
@"document.body.appendChild(img);";
[webView stringByEvaluatingJavaScriptFromString:addStr];
//修改id对应的标签文本
NSString *Str = @"var word = document.getElementById('word');"
@"word.innerHTML = 'hello';";
[webView stringByEvaluatingJavaScriptFromString:Str];

//添加脚本方法
NSString *getZoom = @"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"var zoomLevel = function getZoomLevel(){"
"return map.getZoom()"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script)";
[webView stringByEvaluatingJavaScriptFromString:getZoom];
}


使用JSContext
JSContext:Aninstance of JSContext represents a JavaScript execution environment.(一个 Context 就是一个 JavaScript 代码执行的环境,也叫作用域。)
JSValue:Conversionbetween Objective-C and JavaScript types.(JS是弱类型的,ObjectiveC是强类型的,JSValue被引入处理这种类型差异,在Objective-C 对象和 JavaScript 对象之间起转换作用)
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"网页加载完成");
//获取webView的context
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//oc 调 js
[context evaluateScript:@"test1()"];
context[@"printHelloWorld"] = ^() {
//处理不定参数(调用时传的参数)
NSArray *array = [JSContext currentArguments];
for (id item in array) {
NSLog(@"%@", item);
}
NSLog(@"Hello World !");
};
[context evaluateScript:@"printHelloWorld(1,11,111,1111,'jc')"];
JSValue *value = [context evaluateScript:@"1+1"];
NSLog(@"-*-------------------%@", value);
[context evaluateScript:@"var name = 'zhangsan'"];
NSLog(@"-*-------------------%@", context[@"name"]);
}

js 调用其他类的实例方法
JSContext *context = [[JSContext alloc] init];
context[@"ContextObject"] = [[AG_NativeObject alloc] init];
[context evaluateScript:@"ContextObject.log(\"hello javascriptCode\")"];

OC调用js方法
JSValue *function = context[@"factorial"];\\获取js里的factorial方法
JSValue *value = [function callWithArguments:@[@3]];
NSLog(@"%d",[value toInt32]);

你可能感兴趣的:(JSContext、webView)