Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

navigator.share is not working in a WebView

Is there a reason why the navigator.share() JavaScript function is not working inside a WebView of my Android app? When accessing the same URL through the web browser, the native Android share dialog pops up, but not when accessing the URL from the WebView of my app.

  • The URL is using https.
  • The share action is user-triggered by an onClick.
  • setJavaScriptEnabled is set to true.
  • setDomStorageEnabled is also set to true.
like image 816
jerome2710 Avatar asked Oct 09 '18 14:10

jerome2710


1 Answers

Eventually, I used the following settings for my webviews. There is a bit more to it for me than just the navigator.share, but what works for me might work for others. Worth a try.

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAllowContentAccess(true);
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);

mWebView.addJavascriptInterface(new JavaScriptShareInterface(), "AndroidShareHandler");

The AndroidShareHandler will become a global JavaScript function which will be available in the webview and can be triggered by a button click for example:

Java:

package com.your.package;

import android.webkit.JavascriptInterface;

public class JavaScriptShareInterface {
    @JavascriptInterface
    public void share(String url) {
        // your share action
    }
}

JavaScript:

shareButton.addEventListener('click', () => {
    window.AndroidShareHandler.share('https://stackoverflow.com');
});
like image 132
jerome2710 Avatar answered Sep 22 '22 10:09

jerome2710