IOS uses UIWebView to interact with JavaScript in the simplest way, iosuiwebview

Source: Internet
Author: User

IOS uses UIWebView to interact with JavaScript in the simplest way, iosuiwebview

This is for iOS! And the method is very simple !! The verification is feasible !!!

1. UIWebView calls JavaScript Functions:

NSString * strValue = [webView stringByEvaluatingJavaScriptFromString: @ "YourFunctionName ('yourparameter ')"];

The above sentence is to call the custom function YourFunctionName in JavaScript (Pass in the parameter 'yourparameter 'and obtain the return value and assign it to strValue)

2. JavaScript (through UIWebView) calls the ObjC method:

The simplest and most common method is described below !! After the script is written, it can be thrown to Android for execution:

It is to use UIWebView (WebView for Android) to intercept the URL Function !!! Specify a special URL and write it in a script so that the upper layer can intercept the analysis !! For example,

Write in JavaScript:

Window. location. href = "ABCD: // XXXYYYZZZ"

In iOS:

Implement this function under UIWebViewDelegate (do not forget to set webView. delegate = self)

-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType

{

NSString * strXXX = request. URL. resourceSpecifier;

// Assume that the analysis is only "ABCD ://"

Nsange range = [strXXX rangeOfString: @ "ABCD: //"];
If (range. location! = NSNotFound)
{
// Perform the operation here !!!


Return NO; // NO indicates canceling the navigation of this request

}

Return YES;

}

// In Android, using WebView to reload this function can achieve the same effect.

Public boolean shouldOverrideUrlLoading (WebView view, String url ){

Return true;
}

In this way, when JavaScript executes the window. location. href = "ABCD: // XXXYYYZZZ" sentence, the corresponding upper-layer operations will be triggered!

That is, the function of JavaScript to call the upper-layer ObjC function is implemented.

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.