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>

相關文章
相關標籤/搜索