【发布时间】:2011-09-28 18:44:19
【问题描述】:
我想为我的用户提供一个有限的编辑器,使用出色的 CKEditor。
我试图阻止人们添加图像,因此我屏蔽了“源”视图并禁用了“粘贴”按钮(仅保留“粘贴为文本”按钮)。
但是,仍然可以粘贴图像(从网页复制)。 有没有办法防止这种情况发生?
谢谢。
【问题讨论】:
标签: ckeditor
我想为我的用户提供一个有限的编辑器,使用出色的 CKEditor。
我试图阻止人们添加图像,因此我屏蔽了“源”视图并禁用了“粘贴”按钮(仅保留“粘贴为文本”按钮)。
但是,仍然可以粘贴图像(从网页复制)。 有没有办法防止这种情况发生?
谢谢。
【问题讨论】:
标签: ckeditor
这很有用,我使用了 Nis 的解决方案。但问题是,如果你放下一张图片,粘贴事件就会丢失。我进行了更改以防止出现这种情况。
(function(){
var pluginName = 'blockimagepaste';
function replaceImgText(html) {
var ret = html.replace( /<img[^>]*src="data:image\/(bmp|dds|gif|jpg|jpeg|png|psd|pspimage|tga|thm|tif|tiff|yuv|ai|eps|ps|svg);base64,.*?"[^>]*>/gi, function( img ){
alert("Direct image paste is not allowed.");
return '';
});
return ret;
};
function chkImg(editor) {
// don't execute code if the editor is readOnly
if (editor.readOnly)
return;
setTimeout( function() {
editor.document.$.body.innerHTML = replaceImgText(editor.document.$.body.innerHTML);
},100);
};
CKEDITOR.plugins.add( pluginName, {
icons: pluginName,
init : function( editor ){
editor.on( 'contentDom', function() {
// For Firefox
editor.document.on('drop', function(e) {chkImg(editor);});
// For IE
editor.document.getBody().on('drop', function(e) {chkImg(editor);});
editor.document.on( 'paste', function(e) {chkImg(editor);});
// For IE
editor.document.getBody().on('paste', function(e) {chkImg(editor);});
});
} //Init
});
})();
【讨论】:
如果您也希望能够在 Source 视图中防止这种情况发生,只需将此代码添加到您的插件中:
editor.on('key', function(e) {
var html = CKEDITOR.currentInstance.getData();
if (!html) {
return;
}
CKEDITOR.currentInstance.setData(replaceImgText(html));
});
【讨论】:
我知道已经有一段时间了,但如果其他人遇到同样的问题。
您应该使用a plugin as described here 来检查所有图像,如果用户尝试插入图像,则会警告他不允许使用“图像”。
请注意,该插件无法下载,因此我们可能必须创建自己的插件。它很简单。我们只需要将他的代码复制并粘贴到plugin.js 文件中。
CKEDITOR.plugins.add( 'blockimagepaste',
{
init : function( editor )
{
function replaceImgText(html) {
var ret = html.replace( /<img[^>]*src="data:image\/(bmp|dds|gif|jpg|jpeg|png|psd|pspimage|tga|thm|tif|tiff|yuv|ai|eps|ps|svg);base64,.*?"[^>]*>/gi, function( img ){
alert("Direct image paste is not allowed.");
return '';
});
return ret;
}
function chkImg() {
// don't execute code if the editor is readOnly
if (editor.readOnly)
return;
setTimeout( function() {
editor.document.$.body.innerHTML = replaceImgText(editor.document.$.body.innerHTML);
},100);
}
editor.on( 'contentDom', function() {
// For Firefox
editor.document.on('drop', chkImg);
// For IE
editor.document.getBody().on('drop', chkImg);
});
editor.on( 'paste', function(e) {
var html = e.data.dataValue;
if (!html)
return;
e.data.dataValue = replaceImgText(html);
});
} //Init
} );
另一个选项is explained here(我相信它只适用于粘贴事件,在拖动图像时不会做任何事情!)
【讨论】:
您可以使用'paste' event,这样您就可以删除您不喜欢的任何内容。当然,您还应该在保存之前在服务器上验证内容。
【讨论】: