Call jQuery function in Android's WebView from Java?

前端 未结 4 858
心在旅途
心在旅途 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:55

    What you can do is pass a query string parameter when you call the webview (eg. method=hoge).

    Then in your javascript you can check the existance of the param and run the hoge() method accordingly

    Not sure if your interested, but you can also call your android java code from javascript using the android javascript interface, see http://developer.android.com/guide/webapps/webview.html

    0 讨论(0)
  • 2021-01-15 01:56

    well, you can always call a javascript function using loadUrl methode of your webview;

    myWebView.loadUrl("Javascript: alert('test');");
    
    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2021-01-15 02:04

    Just add to your html file a jquery function and named for example show_main_pop :

    function show_main_pop(){
      $('#r_and_h').fadeIn(500);
    }
    

    and in android studio call this function like that:

    webframe.loadUrl("javascript: show_main_pop();")
    
    0 讨论(0)
提交回复
热议问题