[IOS development] UIWebView and JavaScript (JS) callback interaction, iosuiwebview

Source: Internet
Author: User

[IOS development] UIWebView and JavaScript (JS) callback interaction, iosuiwebview
----------------------------------------------- Many articles about the interaction between objc and js are suitable for mac development. The webview of iOS is still different. For details, refer to the idea of interaction between idea and idea. Naturally, from oc to js, you can use stringByEvaluatingJavaScriptFromString. From js to oc, we adopt a clever design. The UIWebView browser intercepts url requests, and the custom url method intercepts interaction requests. Bytes --------------------------------------------------------------------------------------------------

UIWebView is a control used to render the network surface in ios sdk. When displaying a webpage, we can hack the webpage and then display the desired content. The javascript knowledge is required, and the interaction between UIWebView and javascript is stringByEvaluatingJavaScriptFromString:

With this method, we can call javascript through objc and inject javascript.

First, let's take a look at how to call javascript:

 

Here myFunction () is our javascript method.

 

Let's take a look at how javascript is injected. Let's first write a javascript to be injected:

 

Save as test. js and drag it to the resource Group of xcode. Use the code to inject this js (such as in the viewDidLoad method) during initialization ).

 

In this way, the above js is injected, so we can call the js method at any time and how to call it, which is described above.

So can we call the objc method through js. Of course, the principle is to use the UIWebView redirection request to upload some commands to our UIWebView, receive these commands in the delegate method of UIWebView, and execute the corresponding objc method according to the command. This is equivalent to calling the objc method in javascript. It is a little abstract. Let's take a look at the code to understand it.

First, 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, you can call this js method in your html:

[Javascript] 
  1. "Button" value = "Click me! "Onclick =" clickLink () "/>


Finally, we intercepted the redirection request in UIWebVew:

 

 

 

But there is an open-source project that you can see. It allows javascript to call the objective_c method. Call

Http://code.google.com/p/jsbridge-to-cocoa/ for jsbridge-to-cocoa

There are two other related projects

WebViewJavascriptBridge and GAJavaScript are worth your research.

 

Others

Insert js Code

The above functions can be encapsulated into a js function and inserted into the page for 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 Yulin ';"
"Document. forms [0]. submit ();"
"}";"
"Document. getElementsByTagName_r ('head') [0]. a (script);"];
[WebView stringByEvaluatingJavaScriptFromString: @ "myFunction ();"];
}

Look at the above Code:

A. First, create a script tag using js. The type is 'text/javascript '.

B. Insert a string into the tag. This string is a function: myFunction, which enables google to automatically search for keywords.

C. Use stringByEvaluatingJavaScriptFromString to execute the myFunction.

 

1. General call

Encapsulate local data and directly use it as the JS return value. For example, obtain the APPCode of the software.

// Obtain the 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 to js
NSMutableString * _ getApkCode = [[NSMutableString alloc] init];
[_ GetApkCode appendFormat: @ "function _ getApkCode () {"];
[_ GetApkCode appendFormat: @ "return '% @';", _ appcode];
[_ GetApkCode appendString: @ "}"];
[Self. webView stringByEvaluatingJavaScriptFromString: _ getApkCode];
[_ GetApkCode release];

2. Interactive calling with the platform is required

Ideas:

1. Create a request with a certain meaning, 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", tew.all];
If ([url hasPrefix: pre_download])
{

// Download the code ....

}

3. Notes

A. There is an Iframe nested page, js Injection

Page injection JS is injected. In the browser's html, js cannot be called for pages nested with the iframe framework. This is equivalent to calling the JS of the parent page.

You can use the parent + method name to call your injected JS. The number of parent. parent instances can be multiple. This does not affect JavaScript Execution. If you use less parent, it may lead to a failure to call your injected js.

B. There is an interactive processing method. Recommended method. The iphone only provides js interfaces and does not call internal html or other js interfaces.

Example:

Html

Function addDownload ()

{

Urlw.'www.xxx.xxx.zip ';

Download (url); // call the js interface provided by the iphone

AddDownloadTask_ret (); // obtain the download result of the iphone download interface. The local latency method is called here.

}

// Obtain the download result of the iphone download Interface

Function addDownloadTask_ret ()
{

Var obj = getDownloadTaskResult (); // The interface provided here for the iphone. It is responsible for returning the current download execution result if (''! = Obj | undefined! = Obj)

{

// Call some local processing methods.

}

Else

{

SetTimeout ("addDownloadTask_ret2 ();", 1000 );

}

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

Related Article

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.