【iOS开发】UIWebView调用JS点击事件(stringByEvaluatingJavaScriptFromString)

一、场景描述

产品需求是移动端app要调用h5页面,然后监听h5代码中的某个方法,最终执行h5中的具体代码。

二、具体代码

.m文件

@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic,strong) UIWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 初始化
    UIWebView *webView = [[UIWebView alloc] init];
    webView.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-44);
    webView.delegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];

    // 加载资源
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    self.webView = webView;
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 解析html方法,具体事件根据h5要求提供
    NSString *string = [self.webView stringByEvaluatingJavaScriptFromString:@"alert();"];
    NSLog(@"%@",string);
}

test.html资源文件

<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="utf-8">
 <title>OC调用JS点击方法</title>
</head>
<body>
    <input type="button" value="js点击事件" onclick="js_to_oc_click()"/>
    <script type="text/javascript">
    function alert(){
        return "我被成功调起来了";
    }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hanrovey/article/details/76681322