下面是我给大家整理的JS和app交互的方式,有兴趣的同学可以去看看。
一、 H5上代码的对接
要点:1.Object类型的传参、2.同一个与app交互的JS方法、3.脚本方法需内嵌到head里面。
dffddjjjjlj;ljlhhnljkhljhkjf 0
0
下面是我给大家整理的JS和app交互的方式,有兴趣的同学可以去看看。
一、 H5上代码的对接
要点:1.Object类型的传参、2.同一个与app交互的JS方法、3.脚本方法需内嵌到head里面。
dffddjjjjlj;ljlhhnljkhljhkjf 二、 IOS上的代码对接
注意点:#import
#import"ViewController.h" #import@interfaceViewController () @property (nonatomic)UIWebView*webView; @property(nonatomic)JSContext *jsContext; @property(nonnull,strong) UIButton *btn; @end @implementationViewController -(void)viewDidLoad{ [super viewDidLoad]; self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds]; self.webView.delegate = self; [self.view addSubview:_webView]; NSString *str = [[NSBundle mainBundle]pathForResource:@"migi" ofType:@"html"]; [self.webView loadRequest:[NSURLRequestrequestWithURL:[NSURL fileURLWithPath:@"f"]]]; // 在上面添加一个按钮,实现oc端控制h5实现弹alert方法框 self.btn = [[UIButton alloc]initWithFrame:CGRectMake(100,400,100, 40)]; self.btn.backgroundColor = [UIColorredColor]; [self.btn addTarget:selfaction:@selector(showAlert) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.btn]; } -(void)showAlert { //要将script的alert()方法转化为string类型 NSString *alertJs=@"alert('Hello Word')"; [_jsContext evaluateScript:alertJs]; } -(void)webViewDidFinishLoad:(UIWebView*)webView{ _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; _jsContext[@"startFunction"] =^(id obj){ ////这里通过block回调从而获得h5传来的json数据 /*block中捕获JSContexts 我们知道block会默认强引用它所捕获的对象,如下代码所示,如果block中直接使用context也会造成循环引用,这使用我们最好采用[JSContext currentContext]来获取当前的JSContext: */ [JSContext currentContext]; NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ]; NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:nil]; NSLog(@"data %@ ====== ShareUrl %@",obj,dict[@"shareUrl"]); }; // _jsContext.exceptionHandler = ^(JSContext*context, JSValue *exceptionValue) { context.exception = exceptionValue; //比如把js中的方法名改掉,OC找不到相应方法,这里就会打印异常信息 NSLog(@"异常信息:%@", exceptionValue); }; _jsContext[@"testFunction"] =^(id obj){ //这里通过block回调从而获得h5传来的json数据 [JSContext currentContext]; NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ]; NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; // NSLog(@" data %@ ====== ShareUrl%@",obj,dict[@"shareUrl"]); UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:dict[@"title"]message:dict[@"content"]delegate:nilcancelButtonTitle:@"cancel"otherButtonTitles:nil,nil]; [alertView show]; }; } -(BOOL)webView:(UIWebView *)webViewshouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL * url = [requestURL]; //NSLog(@"scheme信息:%@", [urlscheme]); if ([[url scheme] isEqualToString:@"testfunction"]) { NSArray *params =[url.querycomponentsSeparatedByString:@"&"]; NSMutableDictionary *tempDic = [NSMutableDictionarydictionary]; for (NSString *paramStrin params) { NSArray *dicArray = [paramStrcomponentsSeparatedByString:@"="]; if (dicArray.count >1) { NSString *decodeValue =[dicArray[1]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [tempDic setObject:decodeValueforKey:dicArray[0]]; } } UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:tempDic[@"title"]message:tempDic[@"content"]delegate:selfcancelButtonTitle:@"收到"otherButtonTitles:nil]; [alertView show]; NSLog(@"tempDic:%@",tempDic); return NO; } return true; //为yes加载内容,否则不 }
三、 Android代码上的交互
mWebH5.addJavascriptInterface(new MyJavaScriptInterface(this), "android");
mWebH5.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器 view.loadUrl(url); return true;
}
});@JavascriptInterface
publicvoid startFunction(String json){
if(SharedPrefs.getInstance().getUserAccessToken()==null){
Gson gson=new Gson();
finalShareLinkBean shareLinkBean =gson.fromJson(json, ShareLinkBean.class);
LogUtils.i("test",json);
mActivity.runOnUiThread(new Runnable() {
@Override
publicvoid run() {
//跑相关逻辑
}
});
}上面是我整理给大家的js和app交互的方式,希望今后会对大家有帮助。
相关文章:
相关文章
动态生成多页面并实现 URL 路由跳转的 JavaScript 教程
JavaScript 深层对象差异检测:精准提取键值变更的实用教程
深度比较嵌套对象并精准提取差异键的 JavaScript 实战教程
深度比较嵌套对象并精准提取差异键名的 JavaScript 实战教程
JavaScript 中实现数组排序后单次通知的优雅方案
相关标签:
本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门AI工具
相关专题
本专题深入讲解 C++ 中的常见设计模式与架构优化,包括单例模式、工厂模式、观察者模式、策略模式、命令模式等,结合实际案例展示如何在 C++ 项目中应用这些模式提升代码可维护性与扩展性。通过案例分析,帮助开发者掌握 如何运用设计模式构建高质量的软件架构,提升系统的灵活性与可扩展性。
7
2026.01.30
热门下载
相关下载
精品课程
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号