WKWebView

1.创建wkwebview

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;

webview基于UIScrollView父类,

_webview.scrollView.bounces = NO; //如果是,则跳过内容的边缘并再次返回

WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate,设置三个代理

2.//遵守代理

_webview.UIDelegate = self;

_webview.navigationDelegate = self;


3.//设置WKWebViewConfiguration

_wkConfig = [[WKWebViewConfiguration alloc] init];

_wkConfig.userContentController = [[WKUserContentController alloc] init];


往其中加入一些js代码,防止字体变小或者变大

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];

        [_wkConfig.userContentController addUserScript:wkUScript];

//与H5交互添加相对应的方法

[_wkConfig.userContentController addScriptMessageHandler:self name:@"方法名"];

//设置h5页面的最小字体

 _wkConfig.processPool = [[WKProcessPool alloc] init];

        WKPreferences *preferences = [WKPreferences new];

           preferences.javaScriptCanOpenWindowsAutomatically = YES;

           //设定最小字体

           preferences.minimumFontSize= 13.0;

        _wkConfig.preferences= preferences;

//响应H5调用的方法

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

//回传给H5数据

- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation

{

    NSString *jsStr = @"var awsdk = new Object();";

    NSLog(@"jsStr===%@",jsStr);

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self.webview evaluateJavaScript:jsStr completionHandler:^(id _Nullable obj, NSError * _Nullable error) {

            NSLog(@"JS回调:-sss- %@  %@", obj, error);

        }];

    });

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容