ShannonChenCHN / iOSDevLevelingUp

A journey of leveling up iOS development skills and knowledge.
365 stars 105 forks source link

关于WebViewJavascriptBridge的一点疑问 #119

Closed hellogaojun closed 5 years ago

hellogaojun commented 5 years ago

作者,你好,看了你解读的WebViewJavascriptBridge,还是很受益的,但是我有一个问题不是太明白,就是APP客户端(此处单说iOS端)使用这个框架,那么H5端需要怎么做,H5怎么还要去依赖JSBridge这个框架,这个关系是不是有点扯淡了?

ShannonChenCHN commented 5 years ago

@hellogaojun 你好,不知道你说的是不是指要在 H5 里面写下面这段代码,H5 是不需要依赖这个框架的,只是在页面加载时,需要在 JavaScript 里面做一些初始化操作,理论上来讲,在你的 OC 里面加载 h5 网页前 evaluate 这段 js 也是可以的。

function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'https://__bridge_loaded__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}

setupWebViewJavascriptBridge(function(bridge) {

    /* Initialize your app here */

    bridge.registerHandler('JS Echo', function(data, responseCallback) {
        console.log("JS Echo called with:", data)
        responseCallback(data)
    })
    bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
        console.log("JS received response:", responseData)
    })
})

具体建议看看官方文档和源码

hellogaojun commented 5 years ago

谢谢你的解答,我是看我团队的H5端导入JSBridge这个框架,造成了一点误解!

ShannonChenCHN commented 5 years ago

@hellogaojun 不客气~