OC與JS交互之WKWebView

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')
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章