如何使用GWT复制到剪贴板?

Joh*_*dol 15 clipboard gwt

使用Google搜索无法找到相关内容.

有谁知道如何通过GWT Java代码将一些文本复制到剪贴板?我想避免原始的JavaScript注入解决方案.

任何帮助或指针赞赏.

Nim*_*sky 8

只需包装提供的答案/sf/answers/2156722571/

因此,您将任何文本传递给 javascript 本机函数/方法,js 函数会创建一个新元素并复制到剪贴板,并在复制后删除该元素。

新浏览器不需要任何库。

所以 :

public static native void copyTextToClipboard(String text) /*-{
        var textArea = document.createElement("textarea");
        //
        // *** This styling is an extra step which is likely not required. ***
        //
        // Why is it here? To ensure:
        // 1. the element is able to have focus and selection.
        // 2. if element was to flash render it has minimal visual impact.
        // 3. less flakyness with selection and copying which **might** occur if
        //    the textarea element is not visible.
        //
        // The likelihood is the element won't even render, not even a flash,
        // so some of these are just precautions. However in IE the element
        // is visible whilst the popup box asking the user for permission for
        // the web page to copy to the clipboard.
        //

        // Place in top-left corner of screen regardless of scroll position.
        textArea.style.position = 'fixed';
        textArea.style.top = 0;
        textArea.style.left = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textArea.style.width = '2em';
        textArea.style.height = '2em';

        // We don't need padding, reducing the size if it does flash render.
        textArea.style.padding = 0;

        // Clean up any borders.
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';

        // Avoid flash of white box if rendered for any reason.
        textArea.style.background = 'transparent';


        textArea.value = text;

        document.body.appendChild(textArea);

        textArea.select();

        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('Unable to copy');
        }
        document.body.removeChild(textArea);
    }-*/;
Run Code Online (Sandbox Code Playgroud)


Ced*_*ric 5

我使用带有GWT的ZeroClipboard(正如亚历山大所建议的那样),但这并不简单.

请参见http://blog.dandoy.org/2011/09/using-zeroclipboard-with-gwt.html


sus*_*noy 5

以下代码在chrome中对我很好:

public static native void copyToClipboard() /*-{
    var selection = $wnd.getSelection();
    var text =  $doc.getElementById("myElement");
    var range = $doc.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
    $doc.execCommand('copy');
    selection.removeAllRanges();
}-*/;
Run Code Online (Sandbox Code Playgroud)


Ale*_*ett 3

目前似乎没有任何 GWT 库提供此功能。无论如何,不​​可能在所有浏览器中都支持这一点,因为需要 Flash。ZeroClipboard是一个比包装功能更好的库。