Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle callbacks in webview

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

like image 207
sammiwei Avatar asked Feb 22 '23 00:02

sammiwei


1 Answers

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();")
like image 52
Theo Avatar answered Mar 03 '23 21:03

Theo