"Problem arises"
Webview passing objects to the front end through Addjavascriptinterface, everything is fine. But Android has officially warned that this feature is a security risk, instead of using Safe-java-js-webview-bridge to do Java and JS interaction.
The official usage is normal:
<ulclass= "entry"> <Lionclick= "Hostapp.alert (' Hostapp.alert ');">Hostapp.alert</Li> <Lionclick= "Hostapp.toast (' Hostapp.toast ');">Hostapp.toast</Li> </ul>
But if we write the <script> tag in the body, we can't get the Hostapp object:
// Direct call, unable to find Hostapp function() { hostapp.toast (//// onload is called after, still cannot find Hostapp
$ (document). Ready (function() { hostapp.toast (// ) is called after Still can't find Hostapp
Reason
Safe Java-js WebView Bridge the opportunity to inject hostapp-js fragments may also be behind the onload.
If Document.ready Hostapp JS has been injected successfully, in the onload when the call no problem. When the onload Hostapp JS has not begun to inject, you can not find Hostapp.
Solution
Official Offer method:
The JS script layer needs to make a change, that is, the polling state, until the end of the injection success or timeout (1.5s), and then the callback occurs. The implementation is as follows (the following is an example of the transformation of the Zepto.js $.ready () function).
//some actions for the DOM//Define methods that'll be available on all//Zepto Collections$.fn = { //DOM ReadyReadyfunction(callback, jumphostappinject) {varORIGINCB =callback; varMcounter = 0; //try to wait (1500ms timeout) to inject Hostapp Jscallback =function () { if(!window. Hostapp && mcounter++ < SetTimeout (callback, 10);ElseORIGINCB ($); }; //whether to skip waiting for Hostapp injectionif(jumphostappinject) {callback=ORIGINCB; } if(Readyre.test (Document.readystate)) callback ($);ElseDocument.addeventlistener (' domcontentloaded ',function() {Callback ($)},false); return This }, ... ... };
Such a mechanism also explains why the Java layer of JS injection is not placed in the onpagefinish, if so the number of page polling will rise, the waiting time will be longer, and may be timed out. Well, with the above changes, the initial loading of the page needs to trigger the Hostapp call immediately, as follows:
$ (function () { Hostapp.alert ("Hostapp ready Now"
If you are too lazy to modify it, you can download the zepto.js provided by this plugin to GitHub.
Since my project did not use Zepto, when initializing Init, a poll was done according to the official recommended method.
var // Retry Count function () { function isReady () { if// retry 150 times Step + +; SetTimeout (IsReady,ten); Else { init (); } } IsReady ();};
For more instructions and full source code see: Safe java-js Bridge in Android Webview[github]
Reference: http://mobile.51cto.com/aprogram-452011.htm
JavaScript cannot invoke Java object in Webview