Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Javascript: how to execute jquery in webview

I'm building an app which load a webpage in a webview. In that webpage, i need to programmatically click on some links using Jquery. Now, i know how to execute a Javascript code on the webview programmatically (see below):

WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");    


myBrowser.loadUrl("javascript:document.getElementsByid('myWord').click();");

But now, I need to know how implement a Jquery function in my webview; i'm looking for the correct way to manage something like:

myBrowser.loadUrl("jquery:function($("#myAnchor").click(function(event){})");

And which is the correct way to implement the following function?

$("#a_link")[0].click();
like image 330
Stefano Avatar asked Feb 18 '15 07:02

Stefano


2 Answers

If jquery loaded in this page, you can just call this:

webview.setWebViewClient(new WebViewClient() {  
    @Override  
    public void onPageFinished(WebView view, String url) {  
        webview.loadUrl("javascript:(function() { " +  
                    "$("#myAnchor").click(function(event){}" +  
                    "})()");  
    }  
});
like image 55
mazurovEV Avatar answered Sep 29 '22 01:09

mazurovEV


What's your problem? It's about escaping characters?

myBrowser.loadUrl("jquery:function($(\"#myAnchor\").click(function(event){})");
like image 34
Javi Mollá Avatar answered Sep 29 '22 03:09

Javi Mollá