UNPKG

ckeditor5-youtube-embed

Version:

Embed Youtube video's in CKeditor 5

54 lines (40 loc) 1.6 kB
import Command from '@ckeditor/ckeditor5-core/src/command'; export default class InsertYoutubeCommand extends Command { execute() { this.editor.model.change(writer => { const rawYoutubeLink = prompt('Enter Youtube embed URL') let youtubeLink = null if(rawYoutubeLink && typeof rawYoutubeLink === 'string' && rawYoutubeLink.length) { var regex = /^(?:https:\/\/youtu\.be\/|https:\/\/www\.youtube\.com\/watch\?v=|https:\/\/www\.youtube\.com\/embed\/|https:\/\/www\.youtube\.com\/embed\?v=)([A-Za-z0-9\_\-]{5,20})$/ var match = rawYoutubeLink.match(regex) if(match && typeof match[1] === 'string') { youtubeLink = 'https://www.youtube.com/embed/' + match[1] } if(youtubeLink) { /* Insert Youtube component at the current cursor selection */ this.editor.model.insertContent(createYoutube(writer, youtubeLink)) } else { alert('Enter a valid Youtube link to continue') } } }) } refresh() { const model = this.editor.model /* Get actual selection (selected range, or cursor position) */ const selection = model.document.selection /* Get allowed parent, defined in the editing class */ const allowedIn = model.schema.findAllowedParent(selection.getFirstPosition(), 'Youtube') /* Set enabled state */ this.isEnabled = allowedIn !== null } } function createYoutube(writer, link) { const Youtube = writer.createElement('Youtube') const YoutubeFrame = writer.createElement('YoutubeFrame', { src: link }) /* Append title and description to Youtube element */ writer.append(YoutubeFrame, Youtube) return Youtube }