Call jQuery function in Android's WebView from Java?

前端 未结 4 986
心在旅途
心在旅途 2021-01-15 01:19

I am trying to call javascript function which is defined in html like

WebView.loadUrl(\"javascript:hoge()\");

I can call non-jQuery functio

4条回答
  •  难免孤独
    2021-01-15 01:59

    I'm currently working as a JavaScript engineer. From this experience, now I can see what was wrong. It's a scope & timing related issue.
    Functions inside the $(document).ready(function(){}); cannot be called from outside, since they are not global. if you want to call them from outside, you have to make it global. And you have to wait until javascript is fully loaded and ready to be used.

    $(document).ready(function(){
        // make it global function
        window.foo = function(){
            //do something.
        }
    
        // call java method that notifies java that js is ready to use.
        // (you should implement JavascriptInterface class & method)
        window.JsInterface.jsReady();
    })(jQuery);
    
    1. you have to expose functions to Global.
    2. you have to wait until javascript is ready.

提交回复
热议问题