0

I have a WebView that is populated from the server in my app. HTML,that is being fed into it, has a button. Once that button is clicked it should open activity within the app. is this possible?

I could just add a Button widget but was wondering if its possible to have button in WebView

So its something like this.

WebView with HTML containing button -> click it -> open TestActivity

What would i put into

<a href="TestActivity">Test Activity</a>

Hope it makes sense.

Nabdreas
  • 3,327
  • 4
  • 27
  • 30
  • 1
    See http://stackoverflow.com/questions/25364756/getting-values-of-textarea-of-html-in-android/25364977?noredirect=1#comment39581824_25364977 where I answered a "similar" problem - what I said there can be used for your problem too. – Wildcopper Aug 20 '14 at 13:46
  • possible duplicate of [Android Custom URL to open App like in iOS](http://stackoverflow.com/questions/5065982/android-custom-url-to-open-app-like-in-ios) – njzk2 Aug 20 '14 at 13:46
  • or http://stackoverflow.com/questions/15554029/how-do-i-open-any-app-from-my-web-browser-chrome-in-android-what-do-i-have-to – njzk2 Aug 20 '14 at 13:47
  • 1
    Android's [`JavascriptInterface`](http://developer.android.com/reference/android/webkit/JavascriptInterface.html) will let you call *any* java code from javascript in your web view... start Activities, check sensors, etc... – 323go Aug 20 '14 at 13:51

1 Answers1

5

Yes, you can do this. Try something like this.

public class JavaBridge {
    Activity parentActivity;
    public JavaBridge(Activity activity) {
        parentActivity = activity;
    }

    public void launchNewActvity(){    
        Intent intent = new Intent(parentActivity, NewActivity.class);
        parentActivity.startActivity(intent);
    }
}

For your WebView - add this mWebView.addJavascriptInterface(new JavaBridge(this), "JavaBridge");

In your html then you can write something like - <a href = "javascript:window.JavaBridge.launchNewActivity()" />

You can read more about it in here

cliffroot
  • 1,839
  • 17
  • 27
  • Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript, and the method must be public. If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher. – David May 29 '20 at 06:53