您的位置:首页 > 移动开发

WebView 与js交互基础总结

2016-08-02 11:53 387 查看
1、获取Cookie

NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:_theURL]];
NSEnumerator *enumerator = [cookies objectEnumerator];
NSHTTPCookie *cookie;
while (cookie = [enumerator nextObject]) {
NSLog(@"COOKIE{name: %@, value: %@}", [cookie name], [cookie value]);
}


2、获取web标题

NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
self.navigationItem.title = title;


3、禁止复制粘贴等操作

//禁止粘贴复制
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
// Disable callout
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];


4、js与ios之间的交互问题:

(1)JS调用OC的方法wxLogin

JSContext *context = [self.WebViewChat valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"wxLogin"] = ^() {
NSArray *args = [JSContext currentArguments];
for (id obj in args) {
//当OC调用JS的方法和JS调用OC的方法名一致时会出现循环调用
NSLog(@"重复调用%@",obj);
}
};


(2)OC调用JS方法

JSContext *context = [self.HomeWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *js = [NSString stringWithFormat:@"getwxUserInfoByApp('%@','%@','%@','%@');",Dic[@"unionid"],Dic[@"nickname"],Dic[@"sex"],Dic[@"headimgurl"]];
[context evaluateScript:js];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webview cookie javascript