oc和javascript互相调用

概述:javascript

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

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

shouldStartLoadWithRequest。经过调用stringByEvaluatingJavaScriptFromString得到javascript中的数据变化。java

 

一、oc调用javascriptios

建立UIWebView对象,并设置UIWebViewDelegate。web

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

例如:app

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

webView.delegate = self;测试

 [self.view addSubview:webView];

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

 

二、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>

相关文章
相关标签/搜索