OC與JavaScript交互

OC與JavaScript交互#

UIWebView與JavaScript交互的方法是stringByEvaluatingJavaScriptFromString:

OC中調(diào)用JavaScript方法##

[webView stringByEvaluatingJavaScriptFromString:@"first();"];

這里的first()就是JavaScript方法。

OC往JavaScript中注入方法##

  • 首先寫(xiě)一個(gè)需要注入的JavaScript方法:
function showAlert() {
    alert('this is a alert');
}
  • 保存為first.js文件,拖到Xcode項(xiàng)目里面,然后注入這個(gè)js:
// 讀取js
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"first" ofType:@"js"];
NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath]; 
// 注入js
[webView stringByEvaluatingJavaScriptFromString:jsString];
  • 這樣就注入了上面的js,我們隨時(shí)可以調(diào)用js的方法。

JavaScript中調(diào)用OC方法##

原理是利用UIWebView重定向請(qǐng)求,傳一些命令到我們的UIWebView,在UIWebView的代理方法中接收這些命令,并根據(jù)命令執(zhí)行相應(yīng)的OC方法。這樣就相當(dāng)于在JavaScript中調(diào)用OC的方法。

  • 首先寫(xiě)一個(gè)JavaScript方法:
function sendCommand(paramOne,paramTwo) { 
    var url="testapp:"+paramOne+":"+paramTwo;
    document.location = url;  
} 
function clickLink() {  
    sendCommand("alert","嗨");  
} 
  • 然后在html里調(diào)用這個(gè)js方法:
"button" value="Click me!" onclick="clickLink()" />
  • 最后在UIWebView中截獲這個(gè)重定向請(qǐng)求:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
    NSString *requestString = [[request URL] absoluteString];  
    NSArray *components = [requestString componentsSeparatedByString:@":"];  
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {  
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])   
        {  
            UIAlertView *alert = [[UIAlertView alloc]   
                                  initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]  
                                  delegate:self cancelButtonTitle:nil  
                                  otherButtonTitles:@"OK", nil];  
            [alert show];  
        }  
        return NO;  
    }  
    return YES;  
} 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容