The client uses the shouldOverrideUrlLoading
method of the WebViewClient
class to handle the communication between the front end and the client. In this case, how does the front end know the client's processing callback?
details as following:
The front end sends an address of a given protocol, such as getting the current userjsbridge://bridge/userid
The client captures this loading and starts to perform operations, such as writing values to the front endjavaScript:window.userId=12121
window.location.href = "jsbridge://bridge/userid"
console.log(window.userId) //这样貌似拿不到userId
setTimeout(function() {
console.log(window.userId) //这样就可以拿到了。
}, 1000)
What should we do in this scenario?
My understanding is that in order to understand JSBridge, you ultimately need to understand three things. One is how H5 calls Native, the other is how Native calls H5, and the last one is the callback between the two.
How to call Native in H5, the methods on the Internet are all the same, that is, when WebView loads the H5 page, it will call the method in
WebChromeClient
或者是WebviewClient
, select one of them to intercept the H5 data, and hand it over to Native for processingHow Native calls H5, in the final analysis, it’s
webview.loadUrl(javascript:yourFunc(data););
会把数据传给H5并执行H5中的yourFunc
this methodThe callback between the two means that after Native or H5 handles the other party's call, it returns the result to the other party for use by the other party. The essence is to organize the calling function Callback through Map using timestamps or other unique identifiers, that is,
Map(UniqueID,Callback)
,并把此唯一标示UniqueID
传给对方函数,对方执行完毕后,会把这个唯一标示UniqueID
和返回数据data
传回来,然后通过这个UniqueID
找到调用函数CallBack
,然后执行CallBack(data)
It can be seen from your description that you are lost in the second point. You need to write a JS method in H5:
After getting the data in Native, execute:
webview.loadUrl(javascript:getUseID(userid););
The
getUseID
method in H5 will be called up and executed, and the data will be successfully received from NativeIf it is a complete JSBridge, the third point above must be taken into consideration.
You are developing Android Hybrid, and you need a JSBridge
to give you a wheel, written by the big-headed ghost:
https://github.com/JerryMissT...
I recommend a few blogs, they are still good after reading them
http://www.cnblogs.com/dailc/...
http://blog.csdn.net/qq_23547...
http://zjutkz.net/2016/04/17/...