Two ways to interact with ios:js and native

Source: Internet
Author: User

Background:

Uiwebview:ios controls for displaying Web-side content.

1. Core approach:

-(nsstring*) stringbyevaluatingjavascriptfromstring: (NSString *) script;

Script is the JS code, return the result is the result of JS execution. For example, a JS function is

function testfunction (ABC) {  return  ABC;};

WebView calls this JS code as follows:

@" testfunction (' abc ') "  *result = [WebView stringbyevaluatingjavascriptfromstring:js];

2. Important Callbacks:

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype;

WebView each time you need to load a request, call back the method and let the upper layer decide whether to load. Usually intercepted here, for local processing.

Native Call JS:

Essentially a method, through stringbyevaluatingjavascriptfromstring, is synchronous.

The following focus on how JS callback native:

1. Usual method: JS repair by changing doucument loaction or create an invisible iframe, modify its SRC, will trigger the callback WebView shouldstartloadwithrequest, the URL of the parameter request is the newly assigned location or URL, the upper layer intercepts the parameters of this URL, the distribution can be. This is all called asynchronously.

such as JS function:

    var messagingiframe;     = Document.createelement (' iframe ');     = ' None ';    Document.documentElement.appendChild (Messagingiframe);
function Testiosjs () { = "Ios/test/click"; };

When the above JS is triggered, WebView receives the following callback:

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) navigationtype{    *url = request. url.absolutestring;     if ([url Hassuffix:@ "ios/test/click"]) {        //dosomething Want        return  NO;    }     return YES;}

By intercepting the parameters of this request, you can do what native needs to do.

There is an open source code is very good, you can see:https://github.com/marcuswestin/WebViewJavascriptBridge

2. by XMLHttpRequest:

(1) native a Nsurlprotocol class, and through [Nsurlprotocol registerclass:self]; Register yourself.

  (2) JS function creates a XMLHttpRequest object, which can then be set to carry parameters, set to synchronous or asynchronous, and send the request via send.

    functioniosexec () {varEXECXHR =NewXMLHttpRequest (); Execxhr.open (' HEAD ', '/!test_exec? ' + (+NewDate ()),true);//Set Scheme        varVcheadervalue =/.*\ ((. *) \)/.exec (navigator.useragent) [1]; Execxhr.setrequestheader (' VC ', vcheadervalue);//setting parameters, etc.Execxhr.setrequestheader (' RC ', 1); //initiating a requestExecxhr.send (NULL); };

(3) Since step 1 has already registered itself, each client's network request requests the class's + (BOOL) Caninitwithrequest: (Nsurlrequest *) request, which determines whether the request needs to be generated.

  

@implementation testurlprotocol+ (void) initprotocol{    [Nsurlprotocol registerclass:self];} + (BOOL) Caninitwithrequest: (Nsurlrequest *) request{    *url = request. url.absolutestring;     if ([url containsstring:@ "!test_exec"]) {        //do Something    }    return  NO;

(4) by obtaining the parameters of this request, the upper layer can intercept and then perform local related operations.

This method is less used, but can solve the JS synchronous callback native method.

There is also an open source library, you can see: Https://github.com/apache/cordova-ios/tree/master/CordovaLib

The End.

Two ways to interact with ios:js and native

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.