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.
setJavaScriptEnabled
is set to true
.setDomStorageEnabled
is also set to true
.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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With