UIWebView is one of the most commonly used SDKs for iOS, and it has a stringbyevaluatingjavascriptfromstring method to embed JavaScript in the page, In this way we can interact with the page elements in UIWebView in iOS.
Stringbyevaluatingjavascriptfromstring
Using the Stringbyevaluatingjavascriptfromstring method, you need to wait for the UIWebView to be called after the page load is complete. We drag and drop a UIWebView control on the interface. Load Google mobile into this control in load, with the following code:
-(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 manipulate interface elements through JavaScript in the Webviewdidfinishload method.
1. Gets the URL of the current page.
-(void) Webviewdidfinishload: (UIWebView* NSString *currenturl = [WebView Stringbyevaluatingjavascriptfromstring:@ " "";
2. Get the page title:
-(void) Webviewdidfinishload: (UIWebView*) WebView {
NSString*Currenturl=[WebView stringbyevaluatingjavascriptfromstring:@"Document.location.href" NSString *title = [WebView Stringbyevaluatingjavascriptfromstring:document.title "";
3, modifies the value of the interface element.
NSString *js_result = [WebView Stringbyevaluatingjavascriptfromstring:document.getelementsbyname (' Q ') [0 ].value= ' Zhu Qilin '; "];
4, form submission:
NSString *js_result2 = [WebView Stringbyevaluatingjavascriptfromstring: "";
This enables the Google search keyword: "Zhu Qilin" functionality.
5. Inserting JS Code
The above function we can encapsulate into a JS function, the function is inserted into the page 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 Qilin ';"
"Document.forms[0].submit ();"
"}\";"
" "];
[WebView Stringbyevaluatingjavascriptfromstring: "";
Look at the code above:
A, first through the JS create a script tag, type ' Text/javascript '.
b, and then insert a string in this tag, this string is a function:myFunction, this function to implement the Google auto-search keyword function.
c, and then use stringbyevaluatingjavascriptfromstring to execute the MyFunction function.
Demonstrate:
The first step is to open the Google mobile site
Enter the keyword in the second step
Third Step Search
Summary: This article mainly explains the usage of stringbyevaluatingjavascriptfromstring, its function is very powerful, it is very simple to use, through which we can easily operate UIWebView in the page elements.
Original URL: http://blog.csdn.net/cssmhyl/article/details/7790184
UIWebView interaction with JavaScript