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 *) WebView {
NSString *currenturl = [WebView stringbyevaluatingjavascriptfromstring:@ "Document.location.href"];
}
2. Get the page title:
-(void) Webviewdidfinishload: (UIWebView *) WebView {
NSString *currenturl = [WebView stringbyevaluatingjavascriptfromstring:@ "Document.location.href"];
}
3. Modify 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:@ "Document.forms[0].submit (); "];
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 ();"
"}\";"
"document.getElementsByTagName (' head ') [0].appendchild (script);"];
[WebView stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];
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.
Objective-c of OS development and JavaScript interaction