在chrome中,使用window.Clipboard对象,有没有办法捕获粘贴的文本?

use*_*546 9 javascript clipboard google-chrome copy paste

您可以捕获图像.我想弄清楚如何捕获文本.我猜是因为安全原因没有,但我想确定一下.

这个东西还有参考吗?window.Clipboardobject不是v8引擎的一部分,它是chrome浏览器的一部分,我找不到它的官方文档.

Mal*_*alk 13

在您链接的代码中,有一个pasteHandler函数具有以下内容:

// Get the items from the clipboard
        var items = e.clipboardData.items;
        if (items) {
            // Loop through all items, looking for any kind of image
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    // We need to represent the image as a file,
                    var blob = items[i].getAsFile();
                    // and use a URL or webkitURL (whichever is available to the browser)
                    // to create a temporary URL to the object
                    var URLObj = window.URL || window.webkitURL;
                    var source = URLObj.createObjectURL(blob);

                    // The URL can then be used as the source of an image
                    createImage(source);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Chrome开发者框架告诉我items [i]是DataTransferItem (参考)

在参考页面上,我看到了一个kind属性和一个getAsString()方法.后者似乎需要一个回调函数来接收文本作为参数.因此,要使用上述脚本处理文本值,您可以修改我链接的部分,如下所示:

// Get the items from the clipboard
        var items = e.clipboardData.items;
        if (items) {
            // Loop through all items, looking for any kind of image
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    // We need to represent the image as a file,
                    var blob = items[i].getAsFile();
                    // and use a URL or webkitURL (whichever is available to the browser)
                    // to create a temporary URL to the object
                    var URLObj = window.URL || window.webkitURL;
                    var source = URLObj.createObjectURL(blob);

                    // The URL can then be used as the source of an image
                    createImage(source);
                } 
                if (items[i].kind === "string"){
                    items[i].getAsString(function(s) {
                        alert(s);
                    });
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)