Occasionally, WebView is used in iOS to display something, such as news, or an introduction. But the use of not much, now to teach you how to use JS with WebView to interact.
Here's an example of a click image to get a picture path:
1. Test page HTML
<!doctype html>
2. Then we load this section of HTML in the controller
[_webview loadrequest:[nsurlrequest requestwithurl:[[nsbundle mainbundle]urlforresource:@ "work" withExtension:@ " HTML "]];
3. You can see that only one picture is displayed here
4. Load the relevant JS file, named Test.js
function Setimageclickfunction () { var IMGs = document.getelementsbytagname ("img"); for (Var i=0;iHere is the meaning of the two methods (for those unfamiliar with JS Help): The first is to give you all the pictures in the WebView plus click events, the second method is to click on the return image of the URL, about receiving this URL said below.
5. Load this section of JS code in the controller
[_webview stringbyevaluatingjavascriptfromstring:[nsstring Stringwithcontentsofurl:[[nsbundle MainBundle] urlforresource:@ "test" withextension:@ "JS"] encoding:nsutf8stringencoding Error:nil];
You can also directly put the JS code in HTML, the effect is the same.
6. In the proxy method of WebView, we use to call the first JS method
-(void) Webviewdidfinishload: (UIWebView *) webview{ [_webview stringbyevaluatingjavascriptfromstring:@] Setimageclickfunction () "];}
, which means to bind the Click event to the WebView after it has been loaded. Well, finally, the URL is received.
7. Receive the JS return value, when click on the image will implement this proxy method (each load WebView will show), and then we output his return value to see
-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) navigationtype{ nsstring *path=[[request URL] absolutestring]; NSLog (@ "%@", path); return YES;}
2014-10-03 19:39:37.099 webview[31153:60b] Clickimage:file:///users/zhiwupei/library/application%20support/iphone %20simulator/7.1-64/applications/c4f814f6-088d-444f-a508-40ab5c775567/webview.app/test.png
You can see that the console prints the picture path. Because this is a local image, the network picture is the same reason. This makes it possible to click on the image to get to his path.
UIWebView using JS interaction in iOS