WKWebView

turboksiOS160

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


相关文章

多线程举例

多线程举例

举例一:- (void)viewDidLoad {    [super viewDidLoad];    dispatch_queue_t queue = di...

iOS程序的内存布局

iOS程序的内存布局

    代码段:编译之后的代码    数据段:字符串常量:比如NSString * str = @“123”已初始化数据:已初始化的全局变量...

iOS的分类(Category)

iOS的分类(Category)

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

iOS音视频之视频播放

iOS音视频之视频播放

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

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

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

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

iOS短视频开发之---AVPlayer

iOS短视频开发之---AVPlayer

基于原生的AVPlayer + ScrollView实现,包含视频播放、暂停、点赞动画实现。视频是采用的本地视频、需要网络视频请自行添加添加测试。添加方式:  //本地视频 &n...