iOS: 在Object-C中監聽javascript事件( Javascript communicating back with Objective-C code)

來源:互聯網
上載者:User

在iOS開發之Objective-C與JavaScript互動操作 中我們可以通過stringByEvaluatingJavaScriptFromString 去實現在obj-C中擷取到相關節點屬性,添加javascript代碼等功能。但是我們如何監聽到javascript的響應事件呢。在MAC OS中有效API去實現,但iPhone沒有,但我們有一個技巧途徑:

大概思路是:在JavaScript事件響應時,通過設定document.location,這會引發webview的一個delegate方法,從而實現發送通知的效果,即達到監聽的目的。

1、在javascript與webView之間定一個協議約定:

     myapp:myfunction:myparam1:myparam2

2、在javascript中添加代碼:

document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;

3、在webView的delegate方法webView:shouldStartLoadWithRequest:navigationType:  添加

- (BOOL)webView:(UIWebView *)webView2     shouldStartLoadWithRequest:(NSURLRequest *)request     navigationType:(UIWebViewNavigationType)navigationType {     NSString *requestString = [[request URL] absoluteString];    NSArray *components = [requestString componentsSeparatedByString:@":"];     if ([components count] > 1 &&         [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"])         {             NSLog([components objectAtIndex:2]); // param1            NSLog([components objectAtIndex:3]); // param2            // Call your method in Objective-C method using the above...        }        return NO;    }     return YES; // Return YES to make sure regular navigation works as expected.}

 

 

check:http://stackoverflow.com/questions/5671742/send-a-notification-from-javascript-in-uiwebview-to-objectivec

http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/

 

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.