//
// ViewController.m
// oc_js_html
//
// Created by apple on 2019/3/11.
// Copyright © 2019年 suncere. All rights reserved.
//
#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "Masonry.h"
@interface ViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong) WKWebViewConfiguration *wkWebConfig;
@end
@implementation ViewController
-(WKWebViewConfiguration *)wkWebConfig {
if (!_wkWebConfig) {
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
_wkWebConfig = [[WKWebViewConfiguration alloc] init];
_wkWebConfig.userContentController = wkUController;
}
return _wkWebConfig;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.wkWebConfig];
[self loadWebView];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
//開了支持滑動返回
//self.webView.allowsBackForwardNavigationGestures = YES;
[self.view addSubview:self.webView];
[self.wkWebConfig.userContentController addScriptMessageHandler:self name:@"postMessage"];//添加js的方法
[self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.top.bottom.equalTo(@0);
}];
}
-(void)loadWebView {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"];
NSURL *pathURL = [NSURL fileURLWithPath:filePath];
[self.webView loadRequest:[NSURLRequest requestWithURL:pathURL]];
}
#pragma mark - WKScriptMessageHandler
//實現js注入方法的協議方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"postMessage"]) {
NSLog(@"%@", message.body);
}
}
-(void)setLocation:(NSString *)str {
NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",str];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
}
// 頁面開始加載時調用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
}
// 當內容開始返回時調用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
// 頁面加載完成之後調用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//這裏修改導航欄的標題,動態改變
//self.title = webView.title;
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
[self setLocation:@"test"];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"頁面加載失敗");
//[SVProgressHUD showErrorWithStatus:@"頁面加載失敗,請重試..."];
}
// 接收到服務器跳轉請求之後再執行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}
// 在收到響應後,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
//這句是必須加上的,不然會異常
decisionHandler(actionPolicy);
}
// 在發送請求之前,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
//這句是必須加上的,不然會異常
decisionHandler(actionPolicy);
}
@end
js代碼
<script type="text/javascript" charset="utf-8">
mui.init();
try {
window.webkit.messageHandlers.Location.postMessage(null); //調用OC方法“postMessage”
} catch (e) {
//TODO handle the exception
}
//監聽OC的方法
function setLocation(data) {
}
</script>