Skip to content
舞影凌风 edited this page Aug 19, 2017 · 1 revision

1.Gradle 依赖

compile 'com.apkfuns.jsbridge:jsbridge:2.0.10'

2.初始化

JsBridgeConfig.getSetting().setProtocol("JsBridge")
                .setLoadReadyMethod("onJsBridgeReady");

// 注册默认加载模块                
registerDefaultModule(...)                

3.应用

public class WebViewActivity extends Activity {
    private JsBridge jsBridge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 加载模块
        jsBridge = JsBridge.loadModule(...);
        WebView webView = new WebView(this);
        setContentView(webView);
        webView.getSettings().setJavaScriptEnabled(true);
        String url = getIntent().getStringExtra("url");
        if (TextUtils.isEmpty(url)) {
            url = "file:///android_asset/index.html";
        }
        webView.loadUrl(url);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                if (jsBridge.callJsPrompt(message, result)) {
                    return true;
                }
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                jsBridge.injectJs(view);
            }
        });
    }

    @Override
    protected void onDestroy() {
        jsBridge.release();
        super.onDestroy();
    }

}

4.调用

window.onJsBridgeReady = function() {
	JsBridge.module.xxx(...);
}
Clone this wiki locally