之前公司项目中UIWebView,涉及到js 调用oc原生方法.WKWebview项目中没使用,想了解的话,间书中有很多资料. 最近公司的网页用vue框架,跟之前的稍微有变化,记录下用到过的
普通的网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div><a href="test01://loadThisTest">test01</a></div>
<div id="test02">test02</div>
<div id="test03">test03</div>
<script>
window.onload = function () {
let temp = document.getElementById("test02");
temp.onclick = function (e) {
if(window.js_obj){
window.js_obj.testJS();
}
}
document.getElementById("test03").onclick = function(){
if(window.js_obj){
window.js_obj.shareTitleDesc("111","222");
}
};
}
</script>
</body>
</html>
1.URL.scheme拦截的方法
在UIWebView的代理方法中根据URL的scheme判断
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"urlString---%@",request.URL.absoluteString);
NSLog(@"urlScheme---%@",request.URL.scheme);
return YES;
}
以上代理方法分别打印出
urlString---test01://loadThisTest
urlScheme—test01
2.JavaScriptCore
#import <JavaScriptCore/JavaScriptCore.h>
@protocol JSProtocol <JSExport>
-(void)testJS;
-(void)shareTitle:(NSString *)title Desc:(NSString *)desc;
@end
在项目中引入<JavaScriptCore/JavaScriptCore.h>
自定义协议,自定义方法
创建UIWebView,设置代理
@interface Web02ViewController () <UIWebViewDelegate,JSProtocol>
@end
在代理方法中webViewDidFinishLoad设置JSContext. 其他地方实现方法即可
-(void)webViewDidFinishLoad:(UIWebView *)webView{
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"js_obj"] = self;
}
#pragma mark - js
-(void)testJS{
NSLog(@"%s,%zd",__FUNCTION__,__LINE__);
}
-(void)shareTitle:(NSString *)title Desc:(NSString *)desc{
NSLog(@"title--%@--desc---%@",title,desc);
}
3.web页面js
普通的web页面中
<script>
window.onload = function () {
let temp = document.getElementById("test02");
temp.onclick = function (e) {
if(window.js_obj){
window.js_obj.testJS();
}
}
document.getElementById("test03").onclick = function(){
if(window.js_obj){
window.js_obj.shareTitleDesc("111","222");
}
};
}
</script>
vue.js中相应的事件中
js_obj.testJS();
js_obj.shareTitleDesc("111","222");