https://www.cnblogs.com/huaixu/p/5570100.html
https://www.cnblogs.com/qiyiyifan/p/12077700.html
1、webview去除原網址的廣告或者標題
js語句
document.documentElement.getElementsByClassName('這里寫你要消除的空間的class里面的字符串')[0].style.display = 'none'
具體用法:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.getElementsByClassName('adpic')[0].style.display = 'none'"];
}
2. 獲得UIWebView的標題
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
3. 獲取頁面的URL
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
}
4. 修改頁面元素的值
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];
}
5. 表單提交
- (void)webViewDidFinishLoad:(UIWebView *)webView{
一、前言
這個星期面臨一個網頁的需求,需要用到這方面的知識,很久沒看過這方面的代碼了,記錄下吧。
wkwebview的創建和使用就不再提及了,直接看與JS之間的交互吧。
二、內容
1、JS調用OC
window.webkit.messageHandlers.<#對象名#>.postMessage(<#參數#>)
//進行配置控制器 WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; //實例化對象 configuration.userContentController = [WKUserContentController new]; //調用JS方法 [configuration.userContentController addScriptMessageHandler:self name:@"actionEnd"];
#pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name isEqualToString:@"actionEnd"]) { NSDictionary *jsData = message.body; NSLog(@"%@", message.name, jsData); } }
注:對象名要和前端溝通好。前端JS能回傳的類型只能是 NSNumber, NSString, NSDate, NSArray, NSDictionary, NSNull。
2、OC調用JS
// 調用API方法 [self.weexWebView evaluateJavaScript:@“JS” completionHandler:^(id object, NSError * _Nullable error) { NSLog(@"obj:%@---error:%@", object, error); }];