Ios obtains or modifies the content on the webpage. ios obtains and modifies the webpage.
UIWebView is one of the most commonly used sdks for iOS. It has a stringByEvaluatingJavaScriptFromString method that can embed javascript into the page. Through this method, we can interact with webpage elements in UIWebView in iOS.
StringByEvaluatingJavaScriptFromString
To use the stringByEvaluatingJavaScriptFromString method, call the method after the page in UIWebView is loaded. Drag and Drop a UIWebView control on the interface. Load google mobile into this control in Load. 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:
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(); "];
5,Obtain all html
NSString *allHtml = @"document.documentElement.innerHTML";NSString *allHtmlInfo = [webView stringByEvaluatingJavaScriptFromString:allHtml];
6,Get a webpage Value
NSString *htmlNum = @"document.getElementById('title').innerText";NSString *numHtmlInfo = [webView stringByEvaluatingJavaScriptFromString:htmlNum];
7. 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:
If ([title compare: @ "Google"] = NSOrderedSame) {[webView stringByEvaluatingJavaScriptFromString: @ "var script = document. createElement_x ('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_r ('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.