WKWebView

turboksiOS530

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


相关文章

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

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

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

百度地图自定义marker

百度地图自定义marker

#import "HomeViewController.h"#import "PaopaoView.h"@interface HomeViewControlle...

iOS多线程

iOS多线程

多线程常见方案一、GCD的函数:GCD中有2个用来执行任务的函数queue:队列block:任务1.    用同步的方式执行任务dispatch_sync(di...

iOS一行代码搞定自定义AlertView

iOS一行代码搞定自定义AlertView

效果图走一走:使用方式: pod  'KSAlertView'举例使用,单按钮Alert: [[[KSAlertView alloc] initWithT...

iOS图片圆角设置

iOS图片圆角设置

    UIImageView * vv = [[UIImageView alloc] initWithFrame:CGRectMake(50, 500, 250, 25...

Runtime动态创建类

Runtime动态创建类

- (void)viewDidLoad {    [super viewDidLoad];    Class KSObj = objc_allocateClas...