iOS: JS和Native交互的兩種方法


背景:

UIWebView: iOS 用來展示 web 端內容的控件。

1. 核心方法:

- (NSString*)stringByEvaluatingJavaScriptFromString:(NSString *)script;

script 就是 JS 代碼,返回結果為 js 執行結果。 比如一個 JS function 為

function testFunction(abc){
  return abc;
};

webview 調用此 JS 代碼如下:

NSString *js = @"testFunction('abc')";
NSString *result = [webView stringByEvaluatingJavaScriptFromString:js];

 

2. 重要回調:

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

webview 每當需要去加載一個 request 就先回調這個方法,讓上層決定是否 加載。一般在這里截獲,進行本地的處理。

 

Native 調用 JS:

本質就一個方法,通過 stringByEvaluatingJavaScriptFromString,都是同步。

 

下面重點說說JS怎么回調Native:

1.通常方法:js修通過改doucument的loaction或者新建一個看不見的iFrame,修改它的 src,就會觸發回調 webView 的 shouldStartLoadWithRequest,參數 request 的 url 就是新賦值的 location 或者 url,上層截獲這個 url 的參數,對此分發即可。 這個都是異步調用的。

如 JS function:

    var messagingIframe;
    messagingIframe = document.createElement('iframe');
    messagingIframe.style.display = 'none';
    document.documentElement.appendChild(messagingIframe);
function TestIOSJS(){ messagingIframe.src = "ios/test/click"; };

 

當觸發上面的JS時,webview會收到下面的回調:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    if([url hasSuffix:@"ios/test/click"]){
        //do something you want
        return NO;
    }
    return YES;
}

通過截獲這個request的參數就可以做native需要做的事情。

有個開源的代碼挺不錯的,大家可以看看:https://github.com/marcuswestin/WebViewJavascriptBridge

2.通過XMLHttpRequest:

  (1) Native子類化一個NSURLProtocol類,並通過[NSURLProtocol registerClass:self];把自己注冊。

  (2) JS function 創建一個 XMLHttpRequest 對象,然后可以設置攜帶的參數,設置同步或者異步,然后通過 send 發送請求。

 

    function iOSExec(){
        var execXhr = new XMLHttpRequest();
        execXhr.open('HEAD', "/!test_exec?" + (+new Date()), true); //設置scheme
        var vcHeaderValue = /.*\((.*)\)/.exec(navigator.userAgent)[1];
        execXhr.setRequestHeader('vc', vcHeaderValue);//設置參數等
        execXhr.setRequestHeader('rc', 1);
        // 發起請求
        execXhr.send(null);
    };

 

  (3) 因為步驟1已經把自己注冊,所以每個客戶端的網絡請求都會請求這個類 的+(BOOL)canInitWithRequest:(NSURLRequest *)request,讓此決定是否需要生成這個request。

  

@implementation TestURLProtocol

+(void)initProtocol
{
    [NSURLProtocol registerClass:self];
}

+(BOOL)canInitWithRequest:(NSURLRequest *)request{
    NSString *url = request.URL.absoluteString;
    if([url containsString:@"!test_exec"]){
        //do something
    }
    return NO;
}

  (4) 通過獲取這個request的參數,上層可以進行攔截,然后進行本地的相 關操作。 

這個方法比較少用,不過能解決JS同步回調Native的方法。

這里也有一個開源庫,大家可以看一下:https://github.com/apache/cordova-ios/tree/master/CordovaLib

 

The End.

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM