在Chrome上onPaste e.c preventdefault失败

onPaste e.preventDefault Fail on Chrome

本文关键字:preventdefault 失败 onPaste Chrome      更新时间:2023-09-26

我在summernote中有一个contentitable问题。

Codepen: http://codepen.io/anon/pen/LkLYvV

当前行为: Safari/Firefox -当粘贴图像时,它只是显示不允许粘贴,但在Chrome上,它显示不允许粘贴与图像粘贴在一起。

期望行为:完全禁止粘贴图像。

这似乎是指向在Chrome上粘贴事件的问题。

我想防止粘贴图像,所以我添加了e.p preventdefault,但chrome仍然粘贴图像。下面是我的代码和一些用于调试行为的console.log。还有其他方法可以防止铬的粘着吗?

 $('#summernote').summernote({
        height: 300,
        minHeight: 300,
        toolbar: [
            // [groupName, [list of button]]
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['fontsize', ['fontsize']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['insert',['link','picture']]
        ],

        callbacks : {
            onPaste: function (e) {
                e.preventDefault();
                console.log('pasting'); // Chrome shows This
                var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text'); //This actually removes the image because image is not text.

        console.log(bufferText); //Chrome Shows Empty
        console.log(typeof bufferText); //Chrome Shows String
        console.log(bufferText.length); //Chrome Shows 0
        if (bufferText.length == 0) {
            console.log ('in if loop'); //Chrome Shows this in Console
            document.execCommand('insertText', false, 'Paste Not Allowed'); //Chrome wrote "Paste Not Allowed" in contenteditable but the image still get pasted.
            return false;
        }
                if (!bufferText)
                    return true;
                document.execCommand('insertText', false, bufferText);
            }
        }

    });

Update: Throw new error to preventDefault.

目前这是我暂时做的。如果有人能提出比抛出错误更好的方法来停止默认操作就好了。

似乎这个安全设置/chrome浏览器,我必须添加一些东西来获得bufferText

var bufferText = ((ne.originalEvent || ne).clipboardData || window.clipboardData).getData('text/plain') || null;
        if (bufferText == null) {
            throw new Error("Cannot Paste Image");
        }

通过抛出新的错误,我能够停止发布图像,但我可以允许所有其他形式的文本

在你回调onPaste结束时,放一个return false;它应该工作。这就是我使用e.preventDefault()

的方式