stringByEvaluatingJavaScriptFromString
使用stringByEvaluatingJavaScriptFromString方法,需要等UIWebView中的頁面加載完成之後去調用。我們在界面上拖放一個UIWebView控件。在Load中將google mobile加載到這個控件中,代碼如下:
{
[super viewDidLoad];
webview.backgroundColor = [UIColor clearColor];
webview.scalesPageToFit = YES;
webview. delegate = self;
NSURL * url = [[NSURL alloc] initWithString: @" http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp " ];
NSURLRequest * request = [[NSURLRequest alloc] initWithURL:url];
[webview loadRequest:request];
}
我們在webViewDidFinishLoad方法中就可以通過javascript操作界面元素了。
1、獲取當前頁面的url。
NSString * currentURL = [webView stringByEvaluatingJavaScriptFromString: @" document.location.href " ];
}
2、獲取頁面title:
NSString * currentURL = [webView stringByEvaluatingJavaScriptFromString: @" document.location.href " ];
NSString * title = [webview stringByEvaluatingJavaScriptFromString: @" document.title " ];
}
3、修改界面元素的值。
4、表單提交:
這樣就實現了在google搜索關鍵字:“朱祁林”的功能。
5、插入js代碼
上面的功能我們可以封裝到一個js函數中,將這個函數插入到頁面上執行,代碼如下:
" script.type = 'text/javascript'; "
" script.text = \"function myFunction() { "
" var field = document.getElementsByName('q')[0]; "
" field.value='朱祁林'; "
" document.forms[0].submit(); "
" }\"; "
" document.getElementsByTagName('head')[0].appendChild(script); " ];
[webView stringByEvaluatingJavaScriptFromString: @" myFunction(); " ];
看上面的代碼:
a、首先通過js創建一個script的標籤,type爲'text/javascript'。
b、然後在這個標籤中插入一段字符串,這段字符串就是一個函數:myFunction,這個函數實現google自動搜索關鍵字的功能。
c、然後使用stringByEvaluatingJavaScriptFromString執行myFunction函數。