DSBridge is currently the best IOS/Android javascript Bridge on the planet.

DSBridge-IOS:github.com/wendux/DSBr…

DSBridge-Android:github.com/wendux/DSBr…

For comparison with WebViewJavascriptBridge, go to DSBridge VS WebViewJavascriptBridge.

The original link: www.jianshu.com/p/394660510…

Learn about DSBridge in five minutes

Web side

Suppose Native implements two apis: testSyn and testAsyn. Parameters are passed in JSON. TestSyn is a synchronous API that returns results directly after execution. TestAsyn is an asynchronous API that may perform time-consuming operations. Let’s take a look at the Web side of the call.

Javascript call Native

var bridge = getJsBridge();
var str=bridge.call("testSyn", {msg: "testSyn"});
bridge.call("testAsyn", {msg: "testAsyn"}, function (v) {
  alert(v);
})Copy the code

Easy enough to explain! It’s so elegant. If that doesn’t work for you, you might want to check out today’s (soon to be history) most popular WebViewJavascriptBridge, and you’ll come back.

DSBridge is simple, but to give you an idea, here’s the official explanation:

getJsBridge

Function: Get javascript Bridge object.

Other libraries, etc., and I appeared to be used before, don’t need to declare a like WebViewJavascriptBridge setupWebViewJavascriptBridge callback? No, DSBridge doesn’t require any front-end installation code. It’s on demand. The design principle of DSBridge is to make three ways to use the simplest! DSBridge gets the bridge without relying on any callbacks or waiting for the page to finish loading (compare WebViewJavascriptBridge front-end calls if you don’t feel that way). Ps: This works on ios>=8 and Android > SDK19. DSBridge is also compatible with ios7.0-8.0 and Android SDK16-19, but considering the testing coverage, it is recommended that all code be executed after DOM ready.

bridge.call(method,[args,callback])

Function: Call Native API

Method: indicates the API function name

Args: parameter. Type: JSON. This parameter is optional

Callback (String returnValue): required only when calling asynchronous apis.

A synchronous invocation

If you’re an experienced developer, the second line will light up your eyes. Consider one of the biggest criticisms of Node. Currently, none of the cross-platform JsBridges support synchronization, and all calls to fetch values must pass a callback. There will be “callback hell”. DSBridge, however, has changed all that. Support for synchronization is one of the biggest highlights of DSBridge.

The asynchronous call

For more time-consuming apis, DSBridge provides asynchronous support, as shown in the third line above, where you need to pass a callback (if there are no arguments, the callback can be used as a second argument), which will be called when the API is complete, passing the result as a string.

For Native to call Javascript apis

Suppose a webpage provides a function test for native to call, just declare the function as a global function:

function test(arg1,arg2){
  return arg1+arg2;
}Copy the code

If your code is in a closure, just hang the function on the window:

window.test=function(arg1,arg2){
      return arg1+arg2;
}Copy the code

That way it can be called on the end.

The IOS side

Implement the Api

API implementation is very simple, just put the API you want to expose to JS in a class, and then unified registration.

//JsApiTest.m
@implementation JsApiTest
- (NSString *) testSyn:(NSDictionary *) args
{
    return [(NSString *)[args valueForKey:@"msg"] stringByAppendingString:@"[ syn call]"];
}

- (void) testAsyn:(NSDictionary *) args :(void(^) (NSString * _Nullable result))handler
{
    handler([(NSString *)[args valueForKey:@"msg"] stringByAppendingString:@"[ asyn call]"]);
}
@endCopy the code

TestSyn is the synchronization API. Js will wait for Native to return when calling the synchronization API. Js will continue to execute after returning.

TestAsyn is an asynchronous API. When an asynchronous operation is performed, handler.plete is called to notify THE JS, and the callback set in the JS will be called.

To be compatible with ios and Android platforms, conventions for ios Native API interfaces are as follows:

  1. The return value type is NSString if it exists and void if it does not.
  2. Parameters are passed in JSON; DSBridge automatically converts JS parameters to NSDictionary

Note: Methods implemented in JsApiTest. M may not be declared in JsApiTest. H

To register the Api

DWebview * webview=[[DWebview alloc] initWithFrame:bounds];
jsApi=[[JsApiTest alloc] init];
webview.JavascriptInterfaceObject=jsApi;Copy the code

DWebview is provided with the SDK, but you can also use the other two, which are covered later.

So it’s very simple for Native to implement the JS API in a separate class and then register it directly (rather than registering each API separately like some other JS Bridges), and it’s very structured.

Invoke Javascript

DWebView provides two apis for calling JS

// Call the js API (function)- (void)callHandler:(NSString *)methodName arguments:(NSArray * _Nullable)args 
                   completionHandler:(void(^) (NSString * _Nullable))completionHandler;
// Execute arbitrary js code
- (void)evaluateJavaScript:(NSString *)javaScriptString 
                  completionHandler:(void (^ _Nullable)(NSString * _Nullable))completionHandler;Copy the code

In callHandler, methodName is the js function name and args is an array of parameters that can accept numbers, strings, and so on.

The completionHandler is the completion callback used to get the result of the JS execution.

Call time

DWebview can’t properly execute js code until the javascript context is initialized, which is usually done before the entire page is loaded. While DSBridge can catch when the javascript context is initialized, some JS apis may be declared at the end of a page, or even in a separate JS file, If you call the JS API right after the javascript context has been initialized, the JS API might not be loaded yet, so it’s going to fail, so there’s an API that sets up a callback that’s going to be called after the page has loaded, and just to distinguish it from didPageFinished, Our names are as follows:

- (void)setJavascriptContextInitedListener:(void(^_Nullable)(void))callback;Copy the code

If js is actively invoked on the end, do so in this callback. The following is an example:

__block DWebview * _webview=webview;
[webview setJavascriptContextInitedListener:^(){
  [_webview callHandler:@"test"
  arguments:[[NSArray alloc] initWithObjects:@1.@"hello".nil]
  completionHandler:^(NSString *  value){
      NSLog(@ "% @",value);
  }];
}];Copy the code

See the Demo project for a complete example.

About DWebview

There are three WebViews in the SDK:

DWKwebview: inherited from WKWebView, internal js Prompt, alert, confirm functions corresponding to the dialog box.

DUIwebview: Inherits from UIWebView

DWebview: custom view. In ios8.0 or lower, DUIwebview is used. In ios8.0 or greater, DWKwebview is used.

In addition to implementing the API above, all WebViews provide a convenient function for loading web pages:

- (void)loadUrl: (NSString *) url;Copy the code

You can use either one depending on your business, but DWebview is generally preferred because it is more resource-efficient and efficient on new devices.

DWebview also provides a number of other apis and properties. For details, see its header file.

- (id _Nullable) getXWebview;Copy the code

It can return the actual WebView used inside the DWebview. The value will be one of the instances of DUIwebview and DWKwebview. You can tell by isKindOfClass that the feed function is mainly used to extend the DWebview. LoadRequest loadRequest loadRequest loadRequest

- (void)loadRequest:(NSURLRequest *)request
{
      id webview=[selfGetXWebview];if([webview isKindOfClass:[DUIwebview class]]){
        [(DUIwebview *)webview loadRequest:request];
    }else{ [(DWKwebview *)webview loadRequest:request]; }}Copy the code

Pay attention to

DWebview already implements alert, Prompt, and comfirm dialog boxes. You can either leave them alone or customize them. It is worth mentioning that js code will block when calling the alert function under normal circumstances as long as the user does not close the Alert dialog box. However, considering that the alert dialog box only has a confirm button, that is to say, no matter the user closes or confirms it, js code flow will not be affected. Therefore, when the alert dialog box pops up in DWebview, js will be returned first, so that JS can continue to execute, and the prompt box can be closed when the user closes. If you want to block an alert, you can customize it. DWebview’s prompt and comfirm implementations are completely ecMA compliant and are blocked.

Do not manually set the Delegate property of the DUIwebview, because the DUIwebview already sets this property internally. If you need to handle the page loading process yourself, set the WebEventDelegate property.

canvassing

If you feel good, please star! Thanks for supporting 😄. If you have any questions, please contact wechat: Demons-du