您的位置:首页 > Web前端 > JavaScript

JS 与 OC 的 交互

2017-08-01 17:26 113 查看
OC调用JS

方法1:

NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JS中alert弹出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];


方法2:

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('这里是JS中alert弹出的message')";
[context evaluateScript:textJS];


JS调用OC

方法1:

.h文件

#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol JavaScriptDelegate <JSExport>
-(void)method:(id)data;
@end
@interface CustomWebView : UIWebView<JavaScriptDelegate,UIWebViewDelegate>
@property (nonatomic,strong)id <JavaScriptDelegate> jsDelegate;
@property (nonatomic,strong)JSContext * jsContext;
@end
.m文件

#import "CustomWebView.h"

@implementation CustomWebView
-(instancetype)initWithFrame:(CGRect)frame{
if (self=[super initWithFrame:frame]) {
self.delegate=self;
}
return self;
}
-(void)setUp{
self.jsContext=[self valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.jsContext[@"native"]=self;
self.jsDelegate=self;
}
-(void)method:(id)data{
NSLog(@"%@", data);
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
[self setUp];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: