WKWebView

turboksiOS955

<!DOCTYPE html>


<head>

    <title>HTML</title>

    <meta charset="utf-8">

        </head>


<style type='text/css'>

    img{

        cursor:pointer;

    }

   </style>


<body>

    

    <h2 style="text-align:center">Title</h2>

    

    <p style="text-align:center"> <button id="btn1" type = "button" onclick = "clickOne()" > JS调用OC:无参数  </button> </p>

    

    <p style="text-align:center"> <button id="btn2" type = "button" onclick = "clickTwo()"> JS调用OC:带参数  </button> </p>

    

    <p style="text-align:center"> <button id="btn3" type = "button" onclick = "showAlert()" > OC捕获弹框  </button> </p>

    

    <script type = "text/javascript">

        

    function clickOne()

    {

       window.webkit.messageHandlers.clickOne.postMessage({});

    }

    

    function clickTwo()

    {

        window.webkit.messageHandlers.clickTwo.postMessage({"pdid":"大厦1001"});

    }

    

    function showAlert()

    {

        alert("我传递了一个数据");

    }

    

    //OC调用JS改变背景色

    function changeColor()

    {

        document.body.style.backgroundColor = randomColor();

    }

    

    //随机生成颜色

    function randomColor()

    {

        var r=Math.floor(Math.random()*256);

        var g=Math.floor(Math.random()*256);

        var b=Math.floor(Math.random()*256);

        return "rgb("+r+','+g+','+b+")";//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换

    }

    </script>

    

</body>


</html>





#import "KSViewController.h"

#import <WebKit/WebKit.h>

#import <objc/runtime.h>


@interface KSViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView * webView;

@end


@implementation KSViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"修改颜色" style:UIBarButtonItemStyleDone target:self action:@selector(changeColor)];

    self.navigationItem.rightBarButtonItem = item;

    

    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    WKUserScript * wksc = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];

    _webView.UIDelegate = self;

    _webView.navigationDelegate = self;

    _webView.userInteractionEnabled = YES;

    [[_webView configuration].userContentController addScriptMessageHandler:self name:@"clickOne"];

    [[_webView configuration].userContentController addScriptMessageHandler:self name:@"clickTwo"];

    [[_webView configuration].userContentController addUserScript:wksc];

    //请求网页

    NSString * path = [[NSBundle mainBundle] pathForResource:@"KS.html" ofType:nil];

    //    NSURL * url = [NSURL URLWithString:@""];

    //    [_webView loadRequest:[NSURLRequest requestWithURL:url]];

    NSString * url = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    [_webView loadHTMLString:url baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

    [self.view addSubview:_webView];

}


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

    NSString * name = message.name;

    NSDictionary * dic = message.body;

    if ([name isEqual:@"clickTwo"]) {

        [self clickTwo:dic[@"pdid"]];

    }else if ([name isEqual:@"clickOne"]){

        [self clickOne];

    }

}

-(void)clickOne{

    NSLog(@"%s",__func__);

}

-(void)clickTwo:(NSString *)pdid{

    NSLog(@"%@",pdid);

}


- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];

    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler();

    }])];

    [self presentViewController:alertController animated:YES completion:nil];

}


-(void)changeColor{

    NSString * str = @"changeColor()";

    [_webView evaluateJavaScript:str completionHandler:^(id _Nullable item, NSError * _Nullable error) {

        NSLog(@"修改颜色");

    }];

}


@end


相关文章

RunLoop

RunLoop

RunLoop一、基础理论顾名思义1.    运行循环2.    在程序运行过程中循环做一些事情3.    是用户态和内核态之间的交互模式应...

isKindOfClass和isMemberOfClass的区别

isKindOfClass和isMemberOfClass的区别

+ (BOOL)isMemberOfClass:(Class)cls {//    类的元类 与 传入类 对比    return object_getClas...

iOS 之导航渐变,并且跳转返回保持滑动状态

iOS 之导航渐变,并且跳转返回保持滑动状态

导航刚开始进入为透明,根据我们的滑动确定要显示的背景色。先看一下效果图:一:创建demo,将3个界面添加到控制器中,此过程比较简单代码就不上了。二:在第一页的viewDidload中将当前页面的导航设...

iOS音视频之屏幕录制

iOS音视频之屏幕录制

苹果提供了一个自带的录屏功能、但是每次录屏的上边那个小红条的录制状态栏能忍?当然、平时的一些简单的录制就可以了、但是我们开发的程序要求就不一样了、要求高清和全屏。关于这个功能苹果也是提供了对应的类库供...

GCD定时器

GCD定时器

NSTimer依赖于RunLoop,如果RunLoop的任务过于繁重,可能会导致NSTimer不准时。而GCD的定时器会更加准时。- (void)viewDidLoad {   ...

OC对象的本质

OC对象的本质

我们平时编写的oc代码、底层实现其实是C\C++代码OC代码    ——>    C\C++    ——>  &nbs...