WKWebView

turboksiOS193

<!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


相关文章

GCD定时器

GCD定时器

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

iOS音视频之屏幕录制

iOS音视频之屏幕录制

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

RunLoop

RunLoop

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

iOS音视频之视频播放

iOS音视频之视频播放

由于MPMoviePlayerController与MPMoviePlayerViewController在iOS9.0之后被弃用,所以采用AVPlayer以及AVPlayerViewControll...

iOS的block

iOS的block

一:block的本质1.    block本质上是一个OC对象,它内部有个isa指针2.    block是封装了函数调用以及函数调用环境的OC对象3.&nbs...

iOS的分类(Category)

iOS的分类(Category)

一:Category的底层结构定义在objc-runtime-new.h中:struct category_t {    const char *name;   ...