OC与JS交互之WKWebView

来源:互联网 发布:域名购买是永久的吗 编辑:程序博客网 时间:2024/05/22 03:40

OC:

#import "ViewController.h"#import <WebKit/WebKit.h>#import "TwoViewController.h"@interface ViewController ()<UIWebViewDelegate,WKScriptMessageHandler>{    WKWebView *webView;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];    config.preferences.minimumFontSize = 18;     webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];    webView.backgroundColor = [UIColor redColor];    webView.userInteractionEnabled = YES;    [self.view addSubview:webView];    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"JKLTEXT" ofType:@"html"];    NSURL *baseURL = [[NSBundle mainBundle] bundleURL];    [webView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];    WKUserContentController *userC = config.userContentController;    //JS调用OC 添加处理脚本    [userC addScriptMessageHandler:self name:@"showName"];    UIButton *mobileButton = [UIButton buttonWithType:UIButtonTypeCustom];    mobileButton.frame = CGRectMake(10, 500, 60, 40);    [mobileButton setTitle:@"mobile" forState:UIControlStateNormal];    [mobileButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];    [mobileButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:mobileButton];}-(void)btnClick{    if (!webView.loading) {        [webView evaluateJavaScript:@"alertName('来自OC')" completionHandler:nil];    }}//网页加载完成之后调用JS代码才会执行,因为这个时候html页面已经注入到webView中并且可以响应到对应方法- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {    if ([message.name isEqualToString:@"showName"]) {        NSLog(@"message:%@",message.body);    }}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

html:

function alertName(Msg) {    document.getElementById('name').innerHTML =  Msg}function btn1() {    window.webkit.messageHandlers.showName.postMessage('我来自JS')}
0 0
原创粉丝点击