如何从Firefox中的剪贴板获取数据

时间:2012-02-10 21:27:37

标签: javascript jquery firefox clipboard

我想在元素上触发onpaste事件来检索剪贴板中的数据(我想检查剪贴板中是否存在图像并将其上传到服务器中)。它在Chrome上运行得很完美:

$('#textarea')[0].onpaste = function(event)
{
    var items = event.clipboardData.items;

    if (items.length)
    {
        var blob = items[0].getAsFile();
        var fr = new FileReader();

        fr.onload = function(e)
        {
            alert('got it!');
        }

        fr.readAsDataURL(blob);
    }
}

不适用于Firefox:event.clipboardData.items不存在。您是否知道如何在元素中检索onpaste事件?

3 个答案:

答案 0 :(得分:2)

你需要创建一个contenteditable div,它将粘贴图像

var pasteCatcher = $('<div/>',{'id':'container'});
$('body').append(pasteCatcher);
var pasteCatcher = document.getElementById('container');
               pasteCatcher.setAttribute("contenteditable", "");

然后你需要等待粘贴事件并处理它

 window.addEventListener("paste",processEvent);
function processEvent(e) {
//some functionality
}

还要编写代码以从contenteditable div中获取图像数据并将其发送到服务器。

答案 1 :(得分:1)

答案 2 :(得分:0)

当然可以。在此示例中,我使用Ctrl + V后从剪贴板检索图像:

 <div id="foo" style="width: 200px; height: 200px" contenteditable="true">Paste here!</div>
 $('#foo')[0].onpaste = function(e)
{                   
    setTimeout(function()
    {
        var blob = $('#foo img').attr('src');


        $.post('/upload/image', {'data': blob}, function(result)
        {


        }, 'json'); 

    }, 200);
}

适用于具有<div>属性的contenteditable元素,但不适用于<textarea>

P.S。很抱歉回答我自己的问题,但这段代码可能对某人有帮助。