user742030
user742030

Reputation:

Call a javascript function from the activity?

How can I call a function in a HTML doc that is loaded into a webView with a button that is in my activity? ie: An ImageButton (called: bookBtn) is in the title bar of the activity. When it is pressed/tapped, I need it to fire a function in the webView DOM - It basically loads a new HTML doc into the DOM implementing a slide-in effect.

I found plenty of documentation on how to do this from the webView to the activity but not the other way around. Google says it can be done but there really isnt any examples. I tried to tweek the example code they show here but I cant get it to work. Thank for any input.

Below is the function w/in the HTML doc that is loaded into the webView, mWebView:

    <script type="text/javascript">
    $(document).ready(function() {
        function loadTOC(){$.mobile.changePage("docs/1-1.html", "slideup");
        };
    });
</script>

...and w/in my main activity, I tried this as per Google docs but doesn't work:

    ImageButton imageButton = (ImageButton) findViewById(R.id.bookBtn);
    imageButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        mHandler.post(new Runnable() {
            public void run() {
                mWebView.loadUrl("javascript:loadTOC");
            }
        });
        }
    });

Upvotes: 2

Views: 6491

Answers (2)

typo.pl
typo.pl

Reputation: 8942

There are at least two problems in the code:

1) The javascript URL doesn't invoke the loadTOC function, it just references it. What you want is:

mWebView.loadUrl("javascript:loadTOC()");

2) The loadTOC function isn't globally visible AFAIK, so the javascript URL won't be able to access it.

You should also make sure that JavaScript is enabled as no-good-at-coding suggests.

Upvotes: 8

no.good.at.coding
no.good.at.coding

Reputation: 20371

I don't see in here so I'm going to add that you ought to make sure you have

mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setJavaScriptEnabled(true);.

in your Android code

Upvotes: 2

Related Questions