StringByEvaluatingJavaScriptFromString
To use the stringByEvaluatingJavaScriptFromString method, call the method after the page in UIWebView is loaded. We drag and drop a UIWebView control on the interface. Load googlemobile into this control. The Code is as follows:
- - (void)viewDidLoad
- {
- [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];
- }
We can use javascript to operate interface elements in the webViewDidFinishLoad method.
1. Obtain the url of the current page.
- - (void)webViewDidFinishLoad:(UIWebView *)webView {
- NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
- }
2. Obtain the page title:
- - (void)webViewDidFinishLoad:(UIWebView *)webView {
- NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
-
- NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
- }
3. Modify the value of the interface element.
- NSString * js_result = [webView stringByEvaluatingJavaScriptFromString: @ "document. getElementsByName ('q') [0]. value = 'zhu Yulin ';"];
4. Form submission:
- NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "];
In this way, you can search for the keyword "Zhu Yulin" on google.
5. Insert js Code
The above functions can be encapsulated into a js function and inserted into the page for execution. The Code is as follows:
- [WebView stringByEvaluatingJavaScriptFromString: @ "var script = document. createElement ('script ');"
- "Script. type = 'text/javascript ';"
- "Script. text = \" function myFunction (){"
- "Var field = document. getElementsByName ('q') [0];"
- "Field. value = 'zhu Yulin ';"
- "Document. forms [0]. submit ();"
- "}\";"
- "Document. getElementsByTagName ('head') [0]. appendChild (script);"];
- [WebView stringByEvaluatingJavaScriptFromString: @ "myFunction ();"];
Look at the above Code:
A. First, create a script tag using js. The type is 'text/javascript '.
B. Insert a string into the tag. This string is a function: myFunction, which enables google to automatically search for keywords.
C. Use stringByEvaluatingJavaScriptFromString to execute the myFunction.
Demo:
Step 1 open the google mobile website
Step 2 enter keywords
Step 3 search
Summary: This article mainly explains the usage of stringByEvaluatingJavaScriptFromString. It is very powerful and easy to use. Through it, we can easily operate the page elements in uiwebview.
Address: http://www.cnblogs.com/zhuqil/archive/2011/08/03/2126562.html