开发者社区 问答 正文

用JavaScriptCore js调用OC!

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>失败</title>
    <script type="text/javascript">
        function redirectNative() {
            bluewhale.funTo("FAIL");
        }
    </script>
    <style>
        .msg {
            width: 100%;
            margin-top: 30%;
            font-size: 30px;
            font-weight: lighter;
            text-align: center;
        }

        .btn {
            margin-top: 60%;
            background-color: #1478f0;
            position: relative;
            height: 45px;
            bottom: 20%;
            left: 10%;
            width: 80%;
            font-size: 20px;
            color: white;
            font-weight: lighter;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div>
    <div class="msg">${message}</div>
</div>
<div><img src=""/></div>
<button class="btn" onclick="redirectNative()">返回</button>
</body>
</html>

展开
收起
爵霸 2016-03-06 14:27:26 2180 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    如果你是要调用redirectNative(),哪么简单了
    在 - (void)webViewDidFinishLoad:(UIWebView *)webView方法里:

    JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    jsContext[@"redirectNative"] = ^() {
    dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"js_redirectNative调用OC" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    });
    };

    如果你是想实现 bluewhale.funTo("FA1IL"); 调用OC,哪么就稍微复杂点
    (1)协议
    @protocol TestProtocol

    - (void)funTo:(NSString *)some; //这个方法与你js方法同名,同个数的参数
    @end

    (2)

    @interface TestModel()
        @end
        @implementation TestModel
        - (void)funTo:(NSString *)some
        {
    dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:some delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    });
    }
    @end

    (3) 还是在- (void)webViewDidFinishLoad:(UIWebView *)webView方法里:

        JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //如果是funTo调用
        TestModel *tm = [TestModel new];
        jsContext[@"bluewhale"] = tm;

    你可以根据这些自己在整理封装下

    2019-07-17 18:54:33
    赞同 展开评论