Rafael Caetano
Rafael Caetano

Reputation: 46

Run JavaScripts one after another using WebView (Android)

I'm trying to load a web page using WebView in Android and then run several JavaScripts, one after another. To do this I'm trying to use the function onPageFinished to start running a script once the previous one is finished. However, it seems that the function is called only once. Here is my code:

public class MyWebViewClient extends WebViewClient {
    private int state;
    private WebView webView;

    private String[] urls = new String[4];

    public MyWebViewClient(WebView webView, HtmlSelectComponent component) {
        this.webView = webView;

        this.state = 0;
        String option = String.valueOf(component.getOption());
        this.urls[0] = "http://my.web.site/page.aspx";
        this.urls[1] = "javascript:document.getElementById('" + component.getId() + "').value='" + option + "';";
        this.urls[2] = "javascript:(function() {__doPostBack('" + component.getName() + "','');})()";
        this.urls[3] = "javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"; // Obtain the HTML code
        webView.loadUrl(urls[0]);
    }

    @Override
    public void onPageFinished(WebView view, String url)
    {
        state++;
        if(state == 4)
            return; // End of the scripts
        webView.loadUrl(this.urls[state]);
    }
}

The HtmlSelectComponent is a class that holds the component's (which is a dropdown list) name, id and selected option.

What is happening is that the page is being displayed and the onPageFinished is only called once (the "state" variable stops with value 1).

I'm not sure if this is correct because I don't even know if JavaScripts actually call the onPageFinished function and I would like to know the correct way of doing this.

Upvotes: 2

Views: 737

Answers (2)

Rafael Caetano
Rafael Caetano

Reputation: 46

So I found a simple solution. JavaScripts do not call the onPageFinished(); unless they cause a page reload. So, to run several scripts one after another I simply placed them all in a single line, separated by a semi-column like this:

webView.loadUrl("javascript:document.getElementById('" + component.getId() + "').value='" + option + "';(function() {__doPostBack('" + component.getName() + "','');})();javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");

Upvotes: 1

Mahmudul
Mahmudul

Reputation: 470

Process 1 : Simply call it from one JavaScript function's last line (if have no return type) to another Function and you only call the first function and it will call itself when one scripting finished.

Process 2: webview.loadData(); use this method more then one time to push your scripting to webpage when onFinish(); executing.

Upvotes: 0

Related Questions