In-depth Profiling of JSBridge

Image for post
Image for post

Overview

Android Environment

Calling JS in Native

// mWebView = new WebView(this);            
mWebView.loadUrl("javascript: method name ('parameter, needed to be converted to string')");
//Run in UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("javascript: method name ('parameter, needed to be converted to string')");
Toast.makeText(Activity name.this, "call method...", Toast.LENGTH_SHORT).show();
}
});
mWebView.evaluateJavascript("javascript: method name ('parameter, needed to be converted to string')", new ValueCallback() {
@Override
public void onReceiveValue(String value) {
//Here the value refers to the returned value of the corresponding JS method
}
});

Calling Native in JS

WebSettings webSettings = mWebView.getSettings();  
//Android container allows JS scripts
webSettings.setJavaScriptEnabled(true);
//Android container sets the bridge object
mWebView.addJavascriptInterface(getJSBridge(), "JSBridge");
private Object getJSBridge(){  
Object insertObj = new Object(){
@JavascriptInterface
public String foo(){
return "foo";
}
@JavascriptInterface
public String foo2(final String param){
return "foo2:" + param;
}
};
return insertObj;
}
//Call method 1
window.JSBridge.foo(); //Returned: 'foo'
//Call method 2
window.JSBridge.foo2('test');//Returned: 'foo2:test'

iOS Environment

Calling JS in Native

//Swift
webview.stringByEvaluatingJavaScriptFromString("method name (parameter)")
//OC
[webView stringByEvaluatingJavaScriptFromString:@"method name (parameter);"];

Calling Native in JS

#import <JavaScriptCore/JavaScriptCore.h>
-(void)webViewDidFinishLoad:(UIWebView *)webView{
[self hideProgress];
[self setJSInterface];
}
-(void)setJSInterface{ JSContext *context =[_wv valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // API method registered with a name of "foo"
context[@"foo"] = ^() {
//Get the parameter
NSArray *args = [JSContext currentArguments];
NSString *title = [NSString stringWithFormat:@"%@",[args objectAtIndex:0]];
//Do some logic of your own
//A value is returned: 'foo:'+title
return [NSString stringWithFormat:@"foo:%@", title];
};
}
window.top.foo('test');

What is JSBridge?

Image for post
Image for post

JSBridge Implementation Process

URL Scheme

JSBridge: Technical Implementation

Image for post
Image for post

Designing Global Bridge Objects for Interaction Between Native and JS

var JSBridge = window.JSBridge || (window.JSBridge = {});
Image for post
Image for post

Calling Native in JS

//The URL scheme format
//Basically the useful information is the callbackId, handlerName and data at the end
//Native will analyze the scheme after it captures it
var uri = CUSTOM_PROTOCOL_SCHEME://API_Name:callbackId/handlerName?data
//Process of creating the hidden iframe
var messagingIframe = document.createElement('iframe');
messagingIframe.style.display = 'none';
document.documentElement.appendChild(messagingIframe);
//Trigger the scheme
messagingIframe.src = uri;

Native Notifying the API to be Called

Android

public boolean shouldOverrideUrlLoading(WebView view, String url){
//If false is returned, WebView handles the link URL. If true is returned, WebView executes the URL following the procedures
return true;
}

iOS

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *requestString = [[request URL] absoluteString];
//Get the URL scheme for self-processing

Analyzing URL-parameter and Callback Format

Calling JS in Native

JSBridge._handleMessageFromNative(messageJSON);

Registration and Format of the API Method in H5

JSBridge.registerHandler('testH5Func',function(data,callback){
alert('Test data received by the function:'+JSON.stringify(data));
callback&&callback('Test the postback data...');
});

Improving the JSBridge Scheme

Image for post
Image for post
Image for post
Image for post

JSBridge in iOS and Android

Image for post
Image for post

Conclusion

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store