91

I have a simple page with a button, that when pressed, uses the Async Clipboard API to write to the clipboard.

<body>
  <button type="button" onclick="testClipboard();">
    Test Clipboard
  </button>
</body>
function testClipboard() {
  navigator.clipboard.writeText("Clipboard API Test").then(
    v => alert("Success"),
    e => alert("Fail\n" + e));
}

This works on both Chrome and Firefox, desktop and mobile. However on Android Webview it throws the following error:

NotAllowError: Write permission denied.


I figured I need to override WebChromeClient.onPermissionRequest() to grant the permission, but strangely onPermissionRequest() does not seem to have been invoked, and the same error is still thrown.

public class WebChromeController extends WebChromeClient {
  @Override
  public void onPermissionRequest(PermissionRequest request) {
    Log.d("myTag", "Permission request");
    Log.d("myTag", request.getResources().toString());
    request.grant(request.getResources());
  }
}
protected void initWebView() {
  // ...
  myWebView.setWebChromeClient(new WebChromeController());
}

I still get the same error:

NotAllowError: Write permission denied.

Also Logcat logged nothing.


I suspected maybe my Android App requires additional permissions to access the clipboard, but according to https://developer.android.com/about/versions/10/privacy/changes#clipboard-data, my App should have permission when it has focus. Indeed, the following code works:

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("MyLbl", "I have permission");
clipboard.setPrimaryClip(clip);

I also declared the following in AndroidManifest.xml in case the action of requesting permission requires permission:

<uses-permission android:name="android.webkit.PermissionRequest" />

This did nothing.

So it is probably not an issue with App level permission.


What is happening?

How can I get Async Clipboard API calls to work in Webview?


OS: Android 10 Q

Webview: v. 81.0.4044.111

4
  • Similar question, also no answer: stackoverflow.com/questions/61429649/…
    – BDL
    Commented Apr 26, 2020 at 9:36
  • I know nothing about Android, but this article from Google refers to using the Permissions API (of the browser). Commented Apr 27, 2020 at 12:55
  • Could be a bug.
    – Travis J
    Commented Apr 28, 2020 at 2:42
  • @hereticMonkey thx for the link but I don't think it changes anything. It states "attempting to read or write clipboard data will automatically prompt the user for permission if it hasn't already been granted", implying there is no explicit way to request this permission in JS other than just trying to use the clipboard, which I believe is true. As mentioned in the question, when I do that in a Webview environment, onPermissionRequest() has in fact never been invoked.
    – cyqsimon
    Commented Apr 28, 2020 at 9:30

4 Answers 4

82
+25

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");
}
12
  • 3
    I'm surprised that Android Webview didn't implement navigator.permission. Well, that's a shame. I'll use your workaround for the time being. Thank you.
    – cyqsimon
    Commented May 7, 2020 at 5:10
  • 9
    Yes, it is surprising, because other permissions like camera, microphone are working through PermissionRequest inside webview. Commented May 7, 2020 at 5:51
  • @NihthiyaAlthaf In your webpage html/js file, where you want to copy text to the clipboard. Commented Nov 10, 2020 at 12:08
  • 2
    Is there any solution for this only changing client code?
    – Tiago Neto
    Commented Jan 24, 2022 at 19:09
  • 1
    @DavidOli Once you add JS interface to webview object and add some function in the JS interface, you can call that method in javascript using that interface name. In above case, it is 'NativeAndroid', you are free to choose the name for interface. Check this doc for more info: developer.android.com/develop/ui/views/layout/webapps/… Commented Jan 8, 2023 at 4:17
5

I made a trick based on another answer and it is a very simple solution

Enable JS in WebView:

myWebView.getSettings().setJavaScriptEnabled(true)

Then you need to apply this JavaScript code on every page in WebView , you can use onPageStarted method of WebViewClient

myWebView.evaluateJavascript("javascript:navigator.clipboard.writeText = (msg) => { return Android.writeToClipboard(msg); }", null)

Add JS interface:

myWebView.addJavascriptInterface(new WebViewInterface(), "Android")

Create a method to copy the text to clipboard :

class WebViewInterface(private val context: Context) {

@JavascriptInterface
fun writeToClipboard(message: String):Boolean {
        context.copyTextToClipBoard(message)
        return true
    }
}
1
  • I like this answer, the only missing part is that you need to evaluate that javascript every page change, for example in onPageLoaded method of WebViewClient
    – V-master
    Commented Jul 24, 2023 at 17:33
1

Maybe my solution will help someone. I warn you, this is bad solution:) But only working in my case

The point is that when copying with navigator.clipboard.writeText() inside WebView, a DOMException occurs, which calls the onConsoleMessage method of WebChromeClient.

Suitable for those who do not have access to js code.

webView.webChromeClient = object : WebChromeClient() {
            override fun onConsoleMessage(
                message: String?,
                lineNumber: Int,
                sourceID: String?
            ) {
                if(url?.contains("https://some-link.com") == true // the page where the copying takes place
                    && message?.contains("object DOMException") == true) { // navigator.clipboard.writeText() causes this exception
                    evaluateJavascript(
                        "document.getElementById('text_to_be_copied').innerText"
                    ) { text ->
                            val myClipboard: ClipboardManager = getSystemService(requireContext(), ClipboardManager::class.java) as ClipboardManager
                            val clip = ClipData.newPlainText("text", text)
                            myClipboard.setPrimaryClip(clip)
                    }
                }
                super.onConsoleMessage(message, lineNumber, sourceID)
            }
        }
0

Thanks to https://github.com/vueuse/vueuse/blob/main/packages/core/useClipboard/index.ts If page is embedded in Android WebView, use legacyCopy instead of Clipboard API

function legacyCopy(value: string) {
    const ta = document.createElement('textarea')
    ta.value = value ?? ''
    ta.style.position = 'absolute'
    ta.style.opacity = '0'
    document.body.appendChild(ta)
    ta.select()
    document.execCommand('copy')
    ta.remove()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.