UIWebView與JS的交互方式
一,OC調用JS
直接調用蘋果提供的API
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
使用方式:
OC部分:
[self.webView stringByEvaluatingJavaScriptFromString:@"add(1,2)"];
JS部分:
function add(a,b) {
return a+b;
}
二,JS調用OC
OC處理JS的時機在UIWebView的代理方法內
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
使用方式:
JS部分:
function btnClick1() {
location.href = "jsCallBack://method_?param1¶m2"
}
OC部分:
NSString *schem = webView.request.URL.scheme;
if ([schem containsString:@"jsCallBack://"]) {
//action...
return NO;
}
WKWebView與JS的交互方式
一,OC調用JS
調用蘋果提供的API
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
使用方式:
OC部分:
[self.wkWebView evaluateJavaScript:@"playSount()" completionHandler:nil];
JS部分:
function playSount() {
//playSount...
}
二,JS調用OC
OC部分:
這種使用方式比較麻煩一些
1.在創建wkWebView時,需要將被js調用的方法注冊進去
//創建WKWebViewConfiguration文件
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.preferences.minimumFontSize = 10.f;
[config.userContentController addScriptMessageHandler:self name:@"playSound"];
//創建WKWebView類
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
2.在WKScriptMessageHandler代理方法中監聽js的調用
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"playSound"]) {
[self playSound];
}
}
JS部分:
//JS響應事件
function btnClick() {
window.webkit.messageHandlers.playSound.postMessage(null);
}
利用JavaScriptCore庫,WebView與JS的交互
一,OC調用JS
self.jsContent = [[JSContext alloc] init];
NSString *js = @"function add(a,b) {return a + b}";
[self.jsContent evaluateScript:js];
JSValue *jsValue = [self.jsContent[@"add"] callWithArguments:@[@2,@3]];
二,JS調用OC
self.jsContent = [[JSContext alloc] init];
self.jsContent[@"add"] = ^(int a, int b){
NSLog(@"a+b = %d",a+b);
};
[self.jsContent evaluateScript:@"add(10,20)"];
三,JS直接訪問OC對象方法與屬性
1.首先定義一個協議,這個協議遵守JSExport協議
@protocol JSExportTest <JSExport> @property (nonatomic, assign) NSInteger sum; JSExportAs(add, - (NSInteger)add:(int)a b:(int)b); @end
其中JSExportAs()是系統提供的宏,用來聲明在JS環境中方法add與OC環境中方法- (NSInteger)add:(int)a b:(int)b對應。
2.創建一類,遵守JSExportTest協議,並實現它什么的方法與屬性
@interface JSProtolObj : NSObject <JSExportTest>
@end
@implementation JSProtolObj
@synthesize sum = _sum;
- (NSInteger)add:(int)a b:(int)b {
return a+b;
}
- (void)setSum:(NSInteger)sum {
_sum = sum;
}
@end
3.使用方式:
self.jsContent = [[JSContext alloc] init];
self.jsContent.exceptionHandler = ^(JSContext *context, JSValue *exception) {
[JSContext currentContext].exception = exception;
NSLog(@"exception:%@",exception);
};
self.jsContent[@"OCobj"] = self.jsProtolObj;
[self.jsContent evaluateScript:@"OCobj.sum = OCobj.add(10,20)"];
這三種使用方式可以根據實際情況進行適當使用
