IOS WKWebview 和JS交互

IOS WKWebview 使用集錦

1、alert textInput等UI交互解決方法

如果需要與在JS調(diào)用alertconfirmprompt函數(shù)時(shí),通過(guò)JS原生來(lái)處理,而不是調(diào)用JS的alertconfirmprompt函數(shù),那么需要設(shè)置UIDelegate,在得到響應(yīng)后可以將結(jié)果反饋到JS端:
1、首先設(shè)置WKUIDelegate代理

// 與webview UI交互代理
_web_webView.UIDelegate =self;

2、然后:
與JS原生的alertconfirmprompt交互,將彈出來(lái)的實(shí)際上是我們?cè)拇翱冢皇荍S的。在得到數(shù)據(jù)后,由原生傳回到JS:

#pragma mark - WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
     NSLog(@"%s", __FUNCTION__);
}
 
// 在JS端調(diào)用alert函數(shù)時(shí),會(huì)觸發(fā)此代理方法。
// JS端調(diào)用alert時(shí)所傳的數(shù)據(jù)可以通過(guò)message拿到
// 在原生得到結(jié)果后,需要回調(diào)JS,是通過(guò)completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  NSLog(@"%s", __FUNCTION__);
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調(diào)用alert" preferredStyle:UIAlertControllerStyleAlert];
  [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler();
  }]];
  
  [self presentViewController:alert animated:YES completion:NULL];
  NSLog(@"%@", message);
}
 
// JS端調(diào)用confirm函數(shù)時(shí),會(huì)觸發(fā)此方法
// 通過(guò)message可以拿到JS端所傳的數(shù)據(jù)
// 在iOS端顯示原生alert得到Y(jié)ES/NO后
// 通過(guò)completionHandler回調(diào)給JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
  NSLog(@"%s", __FUNCTION__);
  
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調(diào)用confirm" preferredStyle:UIAlertControllerStyleAlert];
  [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler(YES);
  }]];
  [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    completionHandler(NO);
  }]];
  [self presentViewController:alert animated:YES completion:NULL];
  
  NSLog(@"%@", message);
}
 
// JS端調(diào)用prompt函數(shù)時(shí),會(huì)觸發(fā)此方法
// 要求輸入一段文本
// 在原生輸入得到文本內(nèi)容后,通過(guò)completionHandler回調(diào)給JS
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
  NSLog(@"%s", __FUNCTION__);
  
  NSLog(@"%@", prompt);
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調(diào)用輸入框" preferredStyle:UIAlertControllerStyleAlert];
  [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.textColor = [UIColor redColor];
  }];
  
  [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler([[alert.textFields lastObject] text]);
  }]];
  
  [self presentViewController:alert animated:YES completion:NULL];
}
 

2、 WKWebview與JS交互

1、WK調(diào)用JS

[_web_webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable script, NSError * _Nullable error) {
        
    }];

參數(shù)1:@param 是調(diào)用的js方法,并傳值
參數(shù)2:如果JavaScript 代碼出錯(cuò), 可以在completionHandler 進(jìn)行處理.

2、2.js向oc中傳值使用的時(shí)WKWebView注冊(cè)WKScriptMessageHandler代理

 //設(shè)置網(wǎng)頁(yè)的配置文件
 WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration
                                               alloc]init];
///添加js和wkwebview的調(diào)用
_userContentController =[[WKUserContentController alloc]init];
[_userContentController addScriptMessageHandler:self  name:@"aaa"];//注冊(cè)一個(gè)name為alert的js方法
Configuration.userContentController = _userContentController;
_web_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 300,500) configuration:Configuration];
#pragma mark 設(shè)置wkwebview的WKScriptMessageHandler代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message{
    if ([message.name isEqualToString:@"aaa"]) {
        // 打印所傳過(guò)來(lái)的參數(shù),只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull類型
        NSLog(@"%@", message.body);
    }
}

因?yàn)?code>[_userContentController addScriptMessageHandler:self name:@"aaa"];//注冊(cè)一個(gè)name為aaa的js方法所以要在頁(yè)面銷毀的時(shí)候,釋放掉

///關(guān)閉web頁(yè)時(shí)會(huì)釋放內(nèi)存
[_userContentController removeScriptMessageHandlerForName:@"aaa"];

js代碼

window.webkit.messageHandlers.myName.postMessage(message);

3、使用- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL加載HTML標(biāo)簽并且調(diào)取本地的JS文件

1、添加js文件到目錄下,需要注意的是,js文件和圖片一樣屬于資源文件,確保添加到Copy Bundle Resources

42C13F62-A6AB-4C69-AB55-BA5652F39579.png

2、將js文件轉(zhuǎn)為NSData添加到標(biāo)簽中

NSString* pathJs=[[NSBundle mainBundle]pathForResource:@"newsInfo" ofType:@"js"];
        NSData *jsData=[NSData dataWithContentsOfFile:pathJs];
        NSString *jsSource = [NSString stringWithFormat:@"data:js;base64,%@",[jsData base64Encoding]];
        NSString *str_Header=[NSString stringWithFormat:@"<script src=\"%@\"></script>",jsSource ];

3、調(diào)用標(biāo)簽即可

[_web_webView loadHTMLString:[NSString stringWithFormat:@"%@%@",str_Header,str_Html]  baseURL:nil];

4、添加本地圖片,同本地js文件

//編碼圖片
- (NSString *)htmlForJPGImage:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image,1.0);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
    return [NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容