4

I am working on an android project right now and have a question about how to do callbacks in different webviews. I used JSInterface for my project too. Here I have 2 webviews. One has an index page, anther is a overlay(still a html page though.) What I want to do is if any user clicks on some links on the overlay, it should fire a callback function which is written in the java file where the index page was connected to through JSInterface. It might sound confusing, but I have draw something to help make it clear!

Thanks!enter image description here

2
  • I hope I did not understood wrong your question. This should help you stackoverflow.com/questions/3765860/… Commented Dec 28, 2011 at 19:00
  • If the second webview is meant to be an overlay to the first webview, it may be simpler from an architecture perspective and better from a resource utilization perspective to perform the overlay in the HTML and use only one webview. Commented Dec 28, 2011 at 19:22

1 Answer 1

8

You can use a custom URL scheme like myurl://function for your functionality links. Then write an event handler for the WebView's shouldOverrideUrlLoading event in which you decide how to process the URL: either instruct the webview to load it, or do some custom action.

@Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("myurl://")) { // Parse further to extract function and do custom action } else { // Load the page via the webview view.loadUrl(url); } return true; } 

I used startsWith to check the URL for this quick and dirty example, but you should consider using android.net.Uri.parse for parsing URLs.

This should allow you to call the Java function foo() without having to go through the first WebView.

If you want to go through the first webview, then you can call a function on the JSInterface like this (where webView1 is the first WebView retrieved through findViewById):

webView1.loadUrl("javascript:myjsinterface.myjsfunc();") 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your prompt response. The thing I am still confused about is that for the second webview, I did not have JSInterface with it, is there anyway I can pass it back to webview1, and utilize the JSInterface that's already implemented there?
it definitely helped, findViewById is what I was looking for. Thank you so much for the detail explanation!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.