1..webVidew的方法
oc 调js
- (nullableNSString*)stringByEvaluatingJavaScriptFromString:(NSString*)script;
js 调oc
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
NSString*url = request.URL.absoluteString;if([url rangeOfString:@"[sxr://](hiya://)"].location !=NSNotFound) {// url的协议头是sxr
NSLog(@"sxr");returnNO;}returnYES;
通过框架JSContext注入进行交互
- (void)webViewDidFinishLoad:(UIWebView*)webView{
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];//定义好JS要调用的方法,finish就是调用的方法名context[@"finish"]
= ^() {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView*alertView = [[UIAlertViewalloc] initWithTitle:@"方式二"message:@"这是OC原生的弹出窗"delegate:selfcancelButtonTitle:@"收到"otherButtonTitles:nil]; [alertView show];
}); };}
2.wkwebview
首先使用WKWebView.你需要导入
#import <WebKit/WebKit.h>
然后初始化一个WKWebView,设置WKNavigationDelegate,并且执行WKNavigationDelegate的方法.在网页加载成功的时候,我们会调用一些JS代码对网页进行设置.
WKWebView本身提供一个方法进行处理JS代码.javaScriptString:所执行的JS代码
completionHandler:回调
oc 调js
[webView evaluateJavaScript:@"我是JS"completionHandler:^(id_Nullable response,NSError* _Nullable error) { }];
js 调oc
//在JS端调用alert函数时,会触发此代理方法
- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler;//JS端调用confirm函数时,会触发此代理方法。
- (void)webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(BOOLresult))completionHandler;//JS端调用prompt函数时,会触发此代理方法。
- (void)webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt defaultText:(nullableNSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(NSString* _Nullable result))completionHandler;
网友评论