IOSDevelopmentObjective-CAndJavascript InteractionThe operation is the content to be introduced in this article. It mainly explains the usage of stringbyevaluatingjavascriptfromstring. It is very powerful and easy to use, through this, we can easily operate on the page elements in uiwebview.
UiwebviewIs one of the most commonly used 8 sdks for iOS. It has a stringbyevaluatingjavascriptfromstring method that can embed Javascript into the page.IOSModerate andUiwebviewPage element interaction.
- 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 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:
- - (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.