UIWebView and JavaScript (JS) callback Interaction-Standby

Source: Internet
Author: User
Tags script tag

A lot of OBJC and JS Interactive articles are more suitable for Mac development, iOS WebView or something different, reference: Http://blog.sina.com.cn/s/blog_ 693de6100102vhuh.html This article provides a good solution to the UIWebView within the JS and OBJC interaction ideas.naturally, from OC to JS, you can use stringbyevaluatingjavascriptfromstring: to achieve. from JS to OC, using a more ingenious design,UIWebView browser intercepts URL requests, customizing URLs in a way that intercepts interactions please.--------------------------------------------------------------------------------------------------

UIWebView is the control that renders the mesh in the iOS SDK, and when the page is displayed, we can hack the page and display what we want to display. There is a need to use JavaScript knowledge, and the way UIWebView interacts with JavaScript is stringbyevaluatingjavascriptfromstring:

With this approach we can invoke JavaScript via OBJC and inject JavaScript.

First, let's take a look at how to invoke JavaScript:

    1. [WebView stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];

Here MyFunction () is our JavaScript method.

To see what to inject into JavaScript, let's start by writing a JavaScript that needs to be injected:

    1. function Showalert () {
    2. Alert (' In Show alert ');
    3. }

Save As Test.js, and then drag to the resource group under Xcode. Then use the code to inject this JS (as in the Viewdidload method) when initializing.

    1. NSString *filepath = [[NSBundle mainbundle] pathforresource:@ "test" oftype:@ "JS"];
    2. NSString *jsstring = [[NSString alloc] initwithcontentsoffile:filepath];
    3. [WebView stringbyevaluatingjavascriptfromstring:jsstring];

This will inject the above JS, then we can call the JS method at any time, how to invoke, the above is introduced.

Then we can use JS to invoke the OBJC method. Of course, the principle is to use UIWebView Redirect request, pass some commands to our UIWebView, in UIWebView delegate method to receive these commands, and according to the command to execute the corresponding OBJC method. This is equivalent to calling the ObjC method in JavaScript. That's a little bit abstract, just look at the code.

First we write a JavaScript method as follows:

[JavaScript]
    1. function SendCommand (cmd,param) {
    2. var url= "TestApp:" +cmd+ ":" +param;
    3. document.location = URL;
    4. }
    5. function Clicklink () {
    6. SendCommand ("alert", "How are You?") ");
    7. }

Then call this JS method in your HTML, such as:

[JavaScript]
    1. "Button" value= "click me!" onclick= "Clicklink ()"/>


Finally we intercept this redirect request in Uiwebvew:

  1. #pragma mark--
  2. #pragma Mark Uiwebviewdelegate
  3. -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype {
  4. NSString *requeststring = [[Request URL] absolutestring];
  5. Nsarray *components = [requeststring componentsseparatedbystring:@ ":"];
  6. if ([Components Count] > 1 && [(NSString *) [objectatindex:0] isequaltostring:@ "TestApp"]) {
  7. if ([(NSString *) [Components objectatindex:1] isequaltostring:@ "alert"])
  8. {
  9. Uialertview *alert = [[Uialertview alloc]
  10. initwithtitle:@ "Alert from Cocoa Touch" Message:[components Objectatindex:2]
  11. Delegate:self Cancelbuttontitle:nil
  12. otherbuttontitles:@ "OK", nil];
  13. [Alert show];
  14. }
  15. return NO;
  16. }
  17. return YES;
  18. }

But there is an open source project that you can look at, which allows JavaScript to invoke the Objective_c method. Call

Jsbridge-to-cocoa http://code.google.com/p/jsbridge-to-cocoa/

There are two other related projects

Webviewjavascriptbridge and Gajavascript are worth studying slowly.

Other

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:

if ([title Compare: @ "Google"]==nsorderedsame) {
[WebView stringbyevaluatingjavascriptfromstring:@ "var script = document_createelement_x_x (' 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_r (' head ') [0].a (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.

1. General invocation

The local data, encapsulated, directly as the return value of JS. Such as: Access to software Appcode

Get Appcode

Nsarray *_plist_paths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);
NSString *_plist_paths_path=[_plist_paths objectatindex:0];
Nsarray *_plist_array= [_plist_paths_path componentsseparatedbystring:@ "/"];
NSString *_appcode=[[nsstring Alloc]init];
For (NSString *item in _plist_array) {
if ([item length]==36) {
_appcode=item;
Break
}
}
NSLog (@ "Current appcode:%@", _appcode);

Inject into JS
Nsmutablestring *_getapkcode=[[nsmutablestring Alloc]init];
[_getapkcode appendformat:@ "function _getapkcode () {"];
[_getapkcode appendformat:@ "return '%@ ';", _appcode];
[_getapkcode appendstring:@ "}"];
[Self.webview Stringbyevaluatingjavascriptfromstring:_getapkcode];
[_getapkcode release];

2. Need to interact with the platform to invoke

Ideas:

1. Manufacture of requests with certain meanings such as: (location.href= "Download");

2. In method:-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype, intercept:

testmall:http://192.168.1.20:8083 Local test page address

NSString *pre_download=[nsstring stringwithformat:@ "% @downLoad", Testmall];
if ([url hasprefix:pre_download])
{

Download code ....

}

3. Precautions

a. There is an IFRAME nested page, JS injection

page injection JS is injected into the HTML of the browser, for the internal nested IFRAME Framework page , you cannot call to JS. This is the equivalent of invoking the parent page JS.

b. There is an interaction processing method. Recommended use, the iphone is only responsible for providing JS interface, do not call the HTML internal or other JS interface

  

example:

html

function adddownload ()

{

url= ' www.XXX.XXX.zip ';

download (URL);//Invoke the JS interface provided by iphone

adddownloadtask_ret ();//Get the download result of the iphone download interface, here is a local delay method

//get download results from iphone download interface

Function Adddownloadtask_ret ()
{

var obj= Getdownloadtaskresult ();//The interface provided here for the iphone is responsible for returning the results of the current download execution if ('!=obj| | Undefined!=obj)

{

//Invoke some of the local post-processing methods.

}

Else

{

SetTimeout ("Adddownloadtask_ret2 ();", +);

}

}  -------------------------------------------------

UIWebView and JavaScript (JS) callback Interaction-Standby

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.