Plugin para inserir vídeos do YouTube no CKEditor

Depois de alguns dias sem postar em razão de muito trabalho, Curso de Java e 7 matérias na faculdade, estou de volta com mais um plugin para o CKEditor. Muitos usuários leigos não sabem como inserir um vídeo do YouTube no CKEditor, por não saberem manipular o código fonte do texto. Resolvi criar esse plugin para auxiliar nesta tarefa. Basta apenas colar a URL do vídeo ou o código embed gerado pelo YouTube e o sistema se encarrega do resto.

Também é possível gerar código XHTML válido ao inserir um vídeo via URL. Quando o código XHTML válido é gerado, não aparece nenhum elemento na tela indicando um vídeo, mas no código fonte sim. Estranho.


Instalação

Baixe o CKEditor, extraia para alguma pasta, baixe o Plugin e extraia para a pasta plugins do CKEditor. Feito isso, você deve informar ao sistema para usar esse plugin. No arquivo "config.js", localizado na pasta do CKEditor, adicione a seguinte linha:

config.extraPlugins = "youtube";

Você também deve adicionar o botão do plugin na barra de ferramentas do programa. Veja um exemplo:

config.toolbar = [
	['Preview'],
	['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
	['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
	['Link','Unlink','Anchor'],	['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar'],
	['Font','FontSize'],
	['TextColor','BGColor', '-', 'Source', 'YouTube']
];


Código

CKEDITOR.dialog.add( 'youtube', function( editor )
{
	return {
		title : 'Inserir vídeo do YouTube',
		minWidth : 390,
		minHeight : 230,
		contents : [
		{
			id : 'urlTab',
			label : 'URL do Vídeo',
			title : 'URL do Vídeo',
			elements :
			[
				{
					id : 'url',
					type : 'text',
					label : 'Cole a URL do vídeo do YouTube'
				},
				{
					id : 'xhtml',
					type : 'checkbox',
					label : 'XHTML válido'
				},
				{
					id : 'width',
					type : 'text',
					label : 'Largura',
					width : '40'
				},
				{
					id : 'height',
					type : 'text',
					label : 'Altura',
					width : '40'
				}
			]
		},
		{
			id : 'embedTab',
			label : 'Código Embed',
			title : 'Código Embed',
			elements :
			[
				{
					id : 'embed',
					type : 'textarea',
					label : 'Cole o código gerado pelo YouTube (embed)'
				}
			]
		}
        ],
		onOk : function() {
			var editor = this.getParentEditor();
			var contentUrl = this.getValueOf( 'urlTab', 'url' );
			var contentEmbed = this.getValueOf( 'embedTab', 'embed' );
			var xhtml = this.getValueOf( 'urlTab', 'xhtml' );
			var width = this.getValueOf( 'urlTab', 'width' );
			var height = this.getValueOf( 'urlTab', 'height' );

			width = width ? width : 450;
			height = height ? height : 366;

			if ( contentUrl.length > 0 ) {
				if (xhtml == true){
					contentUrl = contentUrl.replace(/^[^v]+v.(.{11}).*/,"$1");
					editor.insertHtml('<object type="application/x-shockwave-flash" style="width:' + width + 'px; height:' + height + 'px;" data="http://www.youtube.com/v/'+contentUrl+'"><param name="movie" value="http://www.youtube.com/v/'+contentUrl+'" /></object>');
				}
				else {
					contentUrl = contentUrl.replace(/^[^v]+v.(.{11}).*/, "$1");
					editor.insertHtml('<object width="' + width + '" height="' + height + '"><param name="movie" value="http://www.youtube.com/v/'+contentUrl+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+contentUrl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + width + '" height="' + height + '"></embed></object>');
				}
			}
			else
			if ( contentEmbed.length > 0 ) {
				editor.insertHtml(contentEmbed);
			}
		},
	buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ]
	};

} );

CKEDITOR.plugins.add( 'youtube',
{
	init : function( editor )
	{
		var command = editor.addCommand( 'youtube', new CKEDITOR.dialogCommand( 'youtube' ) );
		command.modes = { wysiwyg:1, source:1 };
		command.canUndo = false;

		editor.ui.addButton( 'YouTube',
		{
			label : 'Inserir vídeo do YouTube',
			command : 'youtube',
			icon : this.path + 'youtube.png'
		});

		CKEDITOR.dialog.add( 'youtube', 'youtube' );
	}
});


Demo

Você pode ver um demo do sistema funcionando clicando aqui.

Abraço e até a próxima!

23 comentários para “Plugin para inserir vídeos do YouTube no CKEditor”

  1. Muito legal as dicas, bem úteis e simples, realmente seguindo elas resultará em um ganho no desempenho.

  2. Carlos Alan disse:

    Parabéns, concordo com o Francisco a dica de número 2, é uma mão na roda.

  3. Hugo Fabricio disse:

    Otimo Tutorial, voce é o cara!!

  4. Jonnas disse:

    Imagina, que bom que gostou! :D

  5. Pedro Junior disse:

    Dahora esse plugin hein fonini!

    Se vc colocar opção de inserir pelo ID fica completa.

  6. André disse:

    Jonnas muito bom o tutorial. Alterei o plugin para colocar mais uma aba que possui um botão com evento de onClick que realiza a chamada de uma popup. Gostaria de saber como eu faço para buscar o conteúdo da textarea do plugin youtube? Estou tentando a seguinte linha:

    - window.opener.CKEDITOR.instances['editor'].element['$']....... porém não sei como chegar até a textarea. Obrigado

  7. Jonnas disse:

    Se você quer pegar o conteúdo do CKEditor use este comando: CKEDITOR.instances.nome_do_editor.getData();

    Se você quiser puxar o conteúdo dentro do código do plugin, use isto: this.getValueOf('aba', 'id_do_textarea');

  8. Mario disse:

    [b]Muito bom o seu Tutorial, mas, a onde eu coloco o botão do plugin na barra de ferramentas do programa, em qual arquivo do CKEditor que eu adiciono esse código?

    Grato.[/b]

  9. Jonnas disse:

    @Mario

    Você deve colocar os 2 códigos do início desse tutorial no arquivo "config.js". Nesse arquivo você pode definir as opções globais para o editor.

  10. Tylër disse:

    Mas agora o botão de salvar sumiu... O.O

  11. Michael C. disse:

    Show de bola seu tutorial, comecei a trabalhar hoje com CKEditor e estou achando o máximo. Descobrindo a cada minuto funções excelentes. A única dificuldade é encontrar bons tutoriais em portugês como o seu.
    Parabéns!

  12. Jonnas Fonini disse:

    Obrigado Michael. Assim que possível teremos novos tutoriais do CkEditor. Valeu!

  13. Rui disse:

    Bom tutorial, mas será possível mostrar como usar uma combobox?

    values

  14. FIZ A MUDANÇA PARA COLOCAR VIDEOS DO YOUTUBE MAS NÃO FUNCIONOU ...SEGUE O CONFIG COMPLETO JÁ COM AS MUDANÇAS ..VEJA SE FIZ ALGO DE ERRADO POR FAVOR, OBRIGADO.

    /*

    Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.

    For licensing, see LICENSE.html or http://ckeditor.com/license

    */

    CKEDITOR.editorConfig = function( config )

    {

    // Define changes to default configuration here. For example:

    // config.language = 'fr';

    // config.uiColor = '#AADC6E';

    config.skin = 'kama';

    // BARRA DE FERRAMENTAS

    config.toolbar_Full = [

    ['Source'],

    ['NewPage','Preview','-','Templates'],

    ['Cut','Copy','Paste','PasteText','PasteFromWord'],

    ['Print'],

    ['SpellChecker','Scayt'],

    ['Undo','Redo'],

    ['Find','Replace'],

    ['SelectAll','RemoveFormat'],

    // ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],

    ['Maximize','ShowBlocks'],

    ['About'],

    '/',

    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],

    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],

    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],

    ['Link','Unlink','Anchor'],

    ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],

    '/',

    ['Styles','Format','Font','FontSize'],

    ['TextColor','BGColor', '-', 'Source', 'YouTube']

    ];

    CKEDITOR.dialog.add( 'youtube', function( editor )

    {

    return {

    title : 'Inserir vídeo do YouTube',

    minWidth : 390,

    minHeight : 230,

    contents : [

    {

    id : 'urlTab',

    label : 'URL do Vídeo',

    title : 'URL do Vídeo',

    elements :

    [

    {

    id : 'url',

    type : 'text',

    label : 'Cole a URL do vídeo do YouTube'

    },

    {

    id : 'xhtml',

    type : 'checkbox',

    label : 'XHTML válido'

    },

    {

    id : 'width',

    type : 'text',

    label : 'Largura',

    width : '40'

    },

    {

    id : 'height',

    type : 'text',

    label : 'Altura',

    width : '40'

    }

    ]

    },

    {

    id : 'embedTab',

    label : 'Código Embed',

    title : 'Código Embed',

    elements :

    [

    {

    id : 'embed',

    type : 'textarea',

    label : 'Cole o código gerado pelo YouTube (embed)'

    }

    ]

    }

    ],

    onOk : function() {

    var editor = this.getParentEditor();

    var contentUrl = this.getValueOf( 'urlTab', 'url' );

    var contentEmbed = this.getValueOf( 'embedTab', 'embed' );

    var xhtml = this.getValueOf( 'urlTab', 'xhtml' );

    var width = this.getValueOf( 'urlTab', 'width' );

    var height = this.getValueOf( 'urlTab', 'height' );

    width = width ? width : 450;

    height = height ? height : 366;

    if ( contentUrl.length > 0 ) {

    if (xhtml == true){

    contentUrl = contentUrl.replace(/^[^v]+v.(.{11}).*/,"$1");

    editor.insertHtml('');

    }

    else {

    contentUrl = contentUrl.replace(/^[^v]+v.(.{11}).*/, "$1");

    editor.insertHtml('');

    }

    }

    else

    if ( contentEmbed.length > 0 ) {

    editor.insertHtml(contentEmbed);

    }

    },

    buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ]

    };

    } );

    CKEDITOR.plugins.add( 'youtube',

    {

    init : function( editor )

    {

    var command = editor.addCommand( 'youtube', new CKEDITOR.dialogCommand( 'youtube' ) );

    command.modes = { wysiwyg:1, source:1 };

    command.canUndo = false;

    editor.ui.addButton( 'YouTube',

    {

    label : 'Inserir vídeo do YouTube',

    command : 'youtube',

    icon : this.path + 'youtube.png'

    });

    CKEDITOR.dialog.add( 'youtube', 'youtube' );

    }

    });

    config.toolbar_Basic = [

    ['Preview','-','Cut','Copy','Paste','-','Bold','Italic','Underline','Strike','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','Subscript','Superscript','-','Link','Unlink','Image','Table','TextColor','BGColor','FontSize']

    ];

    config.toolbar_toolbarLateral = [

    ['NewPage','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','Copy','Paste','-','Image','-','Copy','Paste','-','Bold','Italic','Underline','-','TextColor','Font','FontSize','Link']

    ];

    config.toolbar = 'Full';

    config.filebrowserBrowseUrl = 'browser/index.php';

    };

  15. Jonnas Fonini disse:

    @Samuel

    Cara, você só deve colocar a primeira parte do código no config. O restante do código é do plugin em si

  16. Alessandro Paulino disse:

    Excelente, Jonnas! Parabéns! Tinha achado um outro plugin chamado MediaEmbed porém o seu facilita ainda mais a vida do usuário leigo.

  17. fabio disse:

    Estou com problemas aqui, nao consigo fazer funcionar o plugin, instalo ele, aparece o botao, clico no botao, passo o link, mas nao aparece o video nem nada.

    Outro problema e que colocando o botao do you tube o de salvar some.

    O que pode ser ? nos de alguma dica por favor.

  18. Aline disse:

    Cara, muitíssimo obrigada!!!

  19. Luciano Lopes disse:

    muito util p mim esse plugin, tava procurando obrigado.

    sugiro alterar o youtube/plugin.js

    e colocar os defaults na largura e altura para usuarios mais leigos nao precisarem colocar um tamanho

    ('default' : '560')

  20. Eduardo disse:

    Ola jonnas td bem? amigo estou mexendo com o plugin de imagem vc poderia midar uma mão? tipo o usuario seleciona a aba enviar o sistema sobe a imagem e volta para a aba info gostaria de saber como ele faz essa volta depois de carregar a imagem ou fazer meu proprio plugin vc poderia mi ajudar?

    att

    Eduardo Hattori

  21. Aldo Barros disse:

    Não deu certo aqui não. Na pasta do Ckeditor no arquivo config.js

    tem apenas as opções:

    /*
    Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
    For licensing, see LICENSE.html or http://ckeditor.com/license
    */

    CKEDITOR.editorConfig = function( config )
    {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
    };
    ..........................
    não intendo o porque, mas naõ aparece nada pra configurar nesse arquivo, nem mesmo as opções da toolbar.

    Se coloco os códigos aí, nada acontece, nem mesmo modifica nada...nem se quer mostra um erro qualquer, muito menos o meno do youtube...help aí galera.

  22. Tarcísio disse:

    E ae galera, Boa tarde! Gostaria de saber se é possível colocar pra aparecer a capa do vídeo ao postar, porque lá aparece um quadradinho branco escrito flash ...

    Desde já agradeço

Comente você também

* Copie este código:

* Cole ou digite o código aqui:

Google