问题
I am wondering how to insert an image by it's URL only (a user gets it from some other website). I need to implement a simple img src="" in CKEditor 5. The problem is that by default, the editor requires me to upload an image while I need to insert an external url.
I have read many related topics (1, 2, 3) but did not find a problem similar to mine. I even do not need the special button, maybe I can somehow just type img src="myurl" (directly typing it inside the editor did not work for me yet) inside CKEditor and then make it to be perceived like an html code after I apply @Html.Raw(Model.Text) to the whole text I have stored in database from CKeditor textarea.
That is what I get after inserting data from the editor to a webpage. I think it is because tags are perceived as text due to security reasons.
P.S. Stack overflow image insertion tool allows to upload image by its url when I click link from the web in dialog. So I want something similar in CKEditor 5.
Will be very grateful for any help!
回答1:
There's a very simple and concise explanation on how to implement this feature, on their documentation: https://ckeditor.com/docs/ckeditor5/latest/framework/guides/creating-simple-plugin.html
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import Image from '@ckeditor/ckeditor5-image/src/image';
import ImageCaption from '@ckeditor/ckeditor5-image/src/imagecaption';
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import imageIcon from '@ckeditor/ckeditor5-core/theme/icons/image.svg';
class InsertImage extends Plugin {
init() {
const editor = this.editor;
editor.ui.componentFactory.add( 'insertImage', locale => {
const view = new ButtonView( locale );
view.set( {
label: 'Insert image',
icon: imageIcon,
tooltip: true
} );
// Callback executed once the image is clicked.
view.on( 'execute', () => {
const imageUrl = prompt( 'Image URL' );
editor.model.change( writer => {
const imageElement = writer.createElement( 'image', {
src: imageUrl
} );
// Insert the image in the current selection location.
editor.model.insertContent( imageElement, editor.model.document.selection );
} );
} );
return view;
} );
}
}
ClassicEditor
.create( document.querySelector( '#editor' ), {
plugins: [ Essentials, Paragraph, Bold, Italic, Image, InsertImage, ImageCaption ],
toolbar: [ 'bold', 'italic', 'insertImage' ]
} )
.then( editor => {
console.log( 'Editor was initialized', editor );
} )
.catch( error => {
console.error( error.stack );
} );
The final result:
I hope it was helpful. :)
来源:https://stackoverflow.com/questions/51642683/ckeditor-5-insert-image-by-external-url