Clipboard API call throws NotAllowedError without invoking onPermissionRequest() Clipboard API call throws NotAllowedError without invoking onPermissionRequest() android android

Clipboard API call throws NotAllowedError without invoking onPermissionRequest()


Clipboard API's writeText method docs says, we need to obtain clipboard-write permission using Permissions API but navigator.permission is undefined in WebView, maybe because they don't want to mix web permissions with Android OS permissions.

There is one more way by which we can copy text to clipboard from Android WebView: by calling native Java method from WebView JavaScript (JS) code.

Enable JS in WebView:

myWebView.getSettings().setJavaScriptEnabled(true);

Add JS interface:

myWebView.addJavascriptInterface(new WebAppInterface(), "NativeAndroid");

Create a method to copy the text to clipboard using android.content.ClipboardManager:

public class WebAppInterface {    @JavascriptInterface    public void copyToClipboard(String text) {        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);        ClipData clip = ClipData.newPlainText("demo", text);        clipboard.setPrimaryClip(clip);    }}

Then call the above method using testClipboard:

function testClipboard() {  navigator.clipboard.writeText("Clipboard API Test").then(    v => alert("Success"),    e => alert("Fail\n" + e));      NativeAndroid.copyToClipboard("Clipboard API Test");}