不少應用爲了節約成本,作出同時在Android與iOS上都能使用的界面,這時就要使用WebView來作。Android和IOS上都有WebView,作起來很省事。固然這時就要考慮如何在Android或iOS中實現與網頁的交互。對iOS而言,包括如何在網頁中調用OC,以及如何在OC中對網頁進行操做。javascript
先將網頁弄到iOS項目中:html
網頁內容以下, 僅供測試:java
- <html>
- <head>
- <meta xmlns="http://www.w3.org/1999/xhtml" http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>這是一個示例html文件</title>
- <script Type='text/javascript'>
- function clickme() {
- alert('點擊按鈕了!');
- }
- </script>
- </head>
- <body>
- <h1>OC與JS互動</h1>
- <h2>blog.csdn.net/xn4545945</h2>
-
- <a href="neng://loadUrl/blog.csdn.net">點擊一下, 連接調用OC函數</a>
- <br/>
- <br/>
- <a href="http://m.baidu.com">js注入, 到baidu頁面上實驗</a>
- </body>
- </html>
1、在OC中調用JSweb
最重要的方法:stringByEvaluatingJavaScriptFromStringxcode
直接上代碼,說明見註釋:瀏覽器
- - (void)webViewDidFinishLoad:(UIWebView *)webView {
-
- NSLog(@"%@", [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
-
-
- [self.webView stringByEvaluatingJavaScriptFromString:@"clickme()"];
- }
2、用超連接來調用OC中方法app
步驟:函數
*1.設置webView的代理<UIWebViewDelegate>
*2.在代理的方法shouldStartLoadWithRequest:中調用.(該方法與網頁的加載有關)
*方法:就是在網頁連接中寫好自定義協議.而後在OC方法中檢查點擊的連接中是否有該協議,有則作相關操做.
代碼以下:oop
- - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
- NSLog(@"%@", request.URL.absoluteString);
- NSString *urlStr = request.URL.absoluteString;
-
-
-
- if ([urlStr hasPrefix:@"neng://"]) {
-
- NSString *urlContent = [urlStr substringFromIndex:[@"neng://" length]];
- NSLog(@"%@", urlContent);
-
-
- NSArray *urls = [urlContent componentsSeparatedByString:@"/"];
- NSLog(@"拆分的結果爲:%@", urls);
-
-
- if (urls.count != 2) {
- return NO;
- }
- NSString *funName = [NSString stringWithFormat:@"%@:", urls[0]];
-
- SEL callFun = NSSelectorFromString(funName);
- # pragma clang diagnostic push
- # pragma clang diagnostic ignored "-Warc-performSelector-leaks"
- [self performSelector:callFun withObject:urls[1]];
- # pragma clang diagnostic pop
- NSLog(@"方法名爲%@, 傳入參數爲%@", funName, urls[1]);
-
- return NO;
- }
-
- return YES;
- }
-
- - (void)loadUrl:(NSString *)urlStr {
- NSLog(@"接收到參數: %@", urlStr);
-
-
- NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", urlStr]];
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
-
- [self.webView loadRequest:request];
- }
3、JS實現注入測試
JS是操做網頁的利器,利用好JS才能真正在應用中爲所欲爲的操做網頁。
核心方法:stringByEvaluatingJavaScriptFromString(與第一個相同,這個是在iOS中操做JS最重要方法)
代碼以下:
- - (void)jsClick {
- [self.webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
- "script.type = 'text/javascript';"
- "script.text = \"function myFunction() { "
- "var field = document.getElementsByName('word')[0];"
- "field.value='WWDC2014';"
- "document.forms[0].submit();"
- "}\";"
- "document.getElementsByTagName('head')[0].appendChild(script);"];
-
- [self.webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
- }
附上例子源碼:http://download.csdn.net/detail/xn4545945/7584575