zoukankan      html  css  js  c++  java
  • oc和javascript互相调用

    概述:

    使用UIWebView加载页面,使用UIWebView的方法stringByEvaluatingJavaScriptFromString调用javascript的方法。

    在javascript中使用document.body.appendChild(iFrame)这样的方式唤起UIWebViewDelegate的方法

    shouldStartLoadWithRequest。通过调用stringByEvaluatingJavaScriptFromString获得javascript中的数据变化。

    1、oc调用javascript

    创建UIWebView对象,并设置UIWebViewDelegate。

    调用stringByEvaluatingJavaScriptFromString方法,执行javascript中的方法。

    例如:

    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 400, 600)];

    webView.delegate = self;

     [self.view addSubview:webView];

    [self->webView stringByEvaluatingJavaScriptFromString:@"self.testAction()"];

    2、javascript调用oc

    oc代码:

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

    {

        NSURL* url = [request URL];

        if ([[url scheme] isEqualToString:kCustomProtocolScheme]) {

            NSString* test = [self->webView stringByEvaluatingJavaScriptFromString:@"self.testAction()"];

            if ([test isEqualToString:@"1"]) {

        //此处添加自定义方法

                return NO;

            }

            else

            {

                return YES;

            }

        }

            return YES;

    }

     javascript代码:

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>good</title>
    </head>
    <style type="text/css">
    canvas{border:dashed 1px #CCC}
    </style>
    <script type="text/javascript">
    var test = '0';

    function call()
    {
    alert("测试开始")
    }
    function testAction()
    {
    return test;
    }

    function js_call_oc()
    {
    var canvas = $$('can');
    var context = canvas.getContext("2d");
    context.clearRect(0,0,400,300);
    var iFrame;
    iFrame = document.createElement("iframe");
    iFrame.setAttribute("src", "ios://jwzhangjie");
    iFrame.setAttribute("style", "display:none;");
    iFrame.setAttribute("height", "0px");
    iFrame.setAttribute("width", "0px");
    iFrame.setAttribute("frameborder", "0");
    document.body.appendChild(iFrame);
    // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉
    iFrame.parentNode.removeChild(iFrame);
    iFrame = null;
    test = "1";
    }

    </script>

    <body onload="call();">
    <canvas id="can" width="400px" height="300px">40000000000</canvas>
    <input type="button" id="btn1" value="调用oc代码!" onclick="js_call_oc()" />
    </body>
    </html>

  • 相关阅读:
    mongodb的常用操作(二)
    mongodb的常用操作
    OpenBSD内核之引导PBR
    OpenBSD内核之引导MBR
    OpenBSD之开篇
    “索引”、大数据的思考
    flume坑之channel.transactionCapacity和HdfsSink.batchSize
    cocos2d-x的CCAffineTransform相关变换实现原理
    MySQL JDBC/MyBatis Stream方式读取SELECT超大结果集
    “全服单世界”的终极目标即“虚拟世界”
  • 原文地址:https://www.cnblogs.com/li-baibo/p/5777222.html
Copyright © 2011-2022 走看看