WKWebView OC与js的交互

Demo

ViewController
import WebKit/WebKit.h

@interface ViewController () WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler

@property (nonatomic,strong) WKWebView *webView;

@property (nonatomic,strong) UIProgressView *proView;

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.proView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.proView.hidden = YES;
    self.proView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 2);

    WKUserContentController *user = [[WKUserContentController alloc] init];
    [user addScriptMessageHandler:self name:@”testName”];

    WKWebViewConfiguration *con = [[WKWebViewConfiguration alloc] init];
    con.userContentController = user;

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:con];

    self.webView.navigationDelegate = self;

    self.webView.UIDelegate = self;

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@”test” ofType:@”html”]]]];

    [self.view addSubview:self.webView];
    [self.view addSubview:self.proView];

    [self.webView addObserver:self forKeyPath:@”estimatedProgress” options:NSKeyValueObservingOptionNew context:nil];

    //[self.view sendSubviewToBack:self.webView];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:0 target:self action:@selector(click:)];

    //OC —> JS

    //JS —> OC

}

pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController )userContentController didReceiveScriptMessage:(WKScriptMessage )message
{
NSLog(@”%@”,message.body);
}

pragma mark - UIDelegate
- (void)webView:(WKWebView )webView runJavaScriptAlertPanelWithMessage:(NSString )message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”弹出框” message:message delegate:nil cancelButtonTitle:@”ok” otherButtonTitles:nil, nil];

[alertView show];
completionHandler();

}

  • (void)webView:(WKWebView )webView runJavaScriptConfirmPanelWithMessage:(NSString )message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
    {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”弹出框” message:message delegate:nil cancelButtonTitle:@”ok” otherButtonTitles:nil, nil];

    [alertView show];
    completionHandler(YES);
    }

  • (IBAction)click:(id)sender {
    [self.webView evaluateJavaScript:@”testFunc(\”ios 传参数\”)” completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
    //NSLog(@”%@”,obj);
    //obj js返回值
    }];
    }

pragma mark - navigationDelegate

//开始
-(void)webView:(WKWebView )webView didStartProvisionalNavigation:(WKNavigation )navigation
{
//
self.proView.hidden = NO;

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

}

//结束
-(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation )navigation
{
self.proView.hidden = YES;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

-(void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionaryNSString ,id> )change context:(void )context
{
self.proView.progress = [change[NSKeyValueChangeNewKey] floatValue];
}

//处理是否允许 跳转 www.baidu.com
//- (void)webView:(WKWebView )webView decidePoliTQForNavigationResponse:(WKNavigationResponse )navigationResponse decisionHandler:(void (^)(WKNavigationResponsePoliTQ))decisionHandler
//{
// if([navigationResponse.response.URL.absoluteString hasPrefix:@”https://www.baidu.com“])
// {
// decisionHandler(WKNavigationResponsePoliTQCancel);
// }
// else{
// decisionHandler(WKNavigationResponsePoliTQAllow);
// }
//}

test.html

!DOCTYPE html>
html>
head>
meta charset=”UTF-8”>
title>/title>

    style type="text/css">
        /*css样式*/
        /*标签名{}*/
        /*p{
            color: red;
            font-size: 24px;
            background: chartreuse;
        }*/
        /*id选择器*/
        /*#red{
            color: red; 
        }

        #blue {
            color: blue;
        }*/

        /*类选择器*/
        .clsRed{
            color: red;
        }

        .clsBlue{
            color: blue;
        }

    /style>

    !--js  swift-->
    script type="text/javascript">  
        function buttonClick()
        {
            window.webkit.messageHandlers.testName.postMessage("js 传参");
        }

        function testFunc(myVar)
        {

            return "213";
            //alert(myVar);
            confirm(myVar);
        }


    /script>
/head>
body>

    h1>一级标题/h1>
    p id="red" class="clsRed">啥地方拿数据库费那事了开发那/p>
    p id="blue" class="clsBlue">asfdasfasfasfafa/p>
    h2>一级标题/h2>
    h3>一级标题/h3>
    h4>一级标题/h4>
    h5>一级标题/h5>

    !--超链接   a -->  
    a href="http://www.baidu.com">百度/a>

    !--图片  img-->
    img src="/img/HBuilder.png"/>

    !--按钮  input   事件必须使用 js 代码-->
    input type="button" value="按钮" onclick="buttonClick()"/>
/body>

/html>

猜你喜欢

转载自blog.csdn.net/weixin_35966617/article/details/53083568