iOS development--Invoke JS and JS injection in Web pages

Source: Internet
Author: User
Tags vars

Get your Web page into your iOS project first:

The contents of the webpage are as follows, for testing only:

[HTML]View PlainCopy 
  1. <html>
  2. <head>
  3. <meta xmlns= "http://www.w3.org/1999/xhtml" http-equiv="Content-type " content="text/html; Charset=utf-8 " />
  4. <title> This is a sample HTML file </title>
  5. <script type=' text/javascript '>
  6. function ClickMe () {
  7. Alert (' Click the button! ‘);
  8. }
  9. </Script>
  10. </head>
  11. <body>
  12. <H1>oc and JS Interactive </H1>
  13. <h2>blog.csdn.net/xn4545945</h2>
  14. < interact with OC!--Custom Protocol --
  15. <a href="neng://loadurl/blog.csdn.net"> click, Link calls OC function </a>
  16. <br/>
  17. <br/>
  18. <a href="http://m.baidu.com">js injection, to the Baidu page experiment </a>
  19. </body>
  20. </html>

First, call JS in OC

The most important method: Stringbyevaluatingjavascriptfromstring

Directly on the code, see note:

[OBJC]View PlainCopy 
  1. Call js====================================*/in/**===========================oc
  2. -(void) Webviewdidfinishload: (UIWebView *) WebView {
  3. the Document object in the//1.oc called JS. (The properties of the document object are first spelled out) can be tested in the browser console input
  4. NSLog (@ "%@", [self. WebView stringbyevaluatingjavascriptfromstring:@ "Document.title"]);
  5. method of invoking JS in//2.oc
  6. [self. WebView stringbyevaluatingjavascriptfromstring:@ "ClickMe ()"];
  7. }


Second, using hyperlinks to call the OC method

Steps:

* * Set WebView proxy <uiwebviewdelegate>*2. Called in the agent's method Shouldstartloadwithrequest:. (This method is related to the loading of the Web page) * Method: is to write a custom protocol in the page link. Then in the OC method, check whether there is a link in the click, and then do the relevant action.

The code is as follows:

[OBJC]View PlainCopy 
  1. /**=========================== WebView link in call oc===============================*/
  2. Agent method for/**webview: Loading page. When returned directly to No, the JS method is called
  3. Where the request parameter is related to sending requests */
  4. -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: (uiwebviewnavigationtype) navigationtype {
  5. NSLog (@ "%@", request.) URL. absolutestring); //You can get the URL to send the request directly
  6. nsstring *urlstr = Request.  URL. absolutestring;
  7. //Format Neng://loadurl/blog.csdn.net Protocol/method/URL
  8. //Determine the protocol header in the link, and if it is neng://, then do the relevant operation
  9. if ([Urlstr hasprefix:@ "neng://"]) {
  10. //Get rid of the back of the protocol header
  11. nsstring *urlcontent = [urlstr substringfromindex:[@ "neng://" length]];
  12. NSLog (@ "%@", urlcontent);
  13. //use/to split the string
  14. Nsarray *urls = [urlcontent componentsseparatedbystring:@ "/"];
  15. NSLog (@ "Split results are:%@", URLs);
  16. //Remove method name
  17. if (URLs. Count! = 2) {
  18. return NO;
  19. }
  20. nsstring *funname = [NSString stringwithformat:@ "%@:", urls[0]]; //method with parameters, plus a colon
  21. SEL callfun = nsselectorfromstring (funname);
  22. Cancel Warning
  23. # pragma clang diagnostic push
  24. # pragma clang diagnostic ignored "-warc-performselector-leaks"
  25. [self performselector:callfun withobject:urls[1]; //Pass the blog.csdn.net as a parameter
  26. # pragma clang diagnostic pop
  27. NSLog (@ "method named%@, incoming parameter is%@", Funname, urls[1]);
  28. return NO;
  29. }
  30. return YES;
  31. }
  32. -(void) Loadurl: (NSString *) urlstr {
  33. NSLog (@ "received parameter:%@", URLSTR);
  34. //Jump to the specified URL--->urlstr
  35. Nsurl *url = [Nsurl urlwithstring:[nsstring stringwithformat:@ "http://%@", Urlstr]];
  36. nsurlrequest *request = [nsurlrequest requestwithurl:url];
  37. [self. WebView Loadrequest:request];
  38. }


Third, JS implementation injection

JS is the operation of the Web page, the use of good JS to really in the application of the arbitrary operation of the Web page.

Core method: Stringbyevaluatingjavascriptfromstring (same as the first one, this is the most important way to operate JS in iOS)

The code is as follows:

[OBJC]View PlainCopy 
  1. /**===========================JS Injection ====================================*/
  2. -(void) Jsclick {
  3. [self. WebView stringbyevaluatingjavascriptfromstring:@ "var script = document.createelement (' Script '); "
  4. "Script.type = ' text/javascript ';"
  5. "script.text = \" Function myFunction () {" //define MyFunction method
  6. "var field = document.getelementsbyname (' word ') [0];"
  7. "field.value= ' WWDC2014 ';"
  8. "Document.forms[0].submit ();"
  9. "}\";"  
  10. "document.getElementsByTagName (' head ') [0].appendchild (script);"]; //Add to Head tab
  11. [self. WebView stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];
  12. }

attached example Source: http://download.csdn.net/detail/xn4545945/7584575

iOS development--Invoke JS and JS injection in Web pages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.