Insert iframe in div from onOk of CKEDITOR.dialog - javascript

I use CKEditor and I have got problem for insert iframe in div element in my editor when the user click on the OK button in my Dialog. This does not work. When the user clicks on the button does nothing happen (I have no error message). So he should shut my popup and insert a div containing my iframe inside my editor
Can you help me ?
this is my code
:
CKEDITOR.dialog.add( 'postVideoDialog', function( editor ) {
return {
title : 'Add Video',
minWidth : 400,
minHeight : 80,
contents :
[
{
id : 'video',
label : 'Add Video',
elements :
[
{
type : 'text',
id : 'url',
label : 'Enter a URL from Vimeo :',
validate : function()
{
var url = this.getValue();
var regex1=/^(http:\/\/)vimeo.com\/[0-9]{3,}$/g;
var regex2=/^(http:\/\/)player.vimeo.com\/video\/[0-9]{3,}$/g;
if(regex1.test(url) || regex2.test(url)){
return true
}else{
alert("Url incorrect");
return false;
}
},
required : true,
commit : function( data )
{
data.url = this.getValue();
}
},
]
}
],
onOk : function()
{
var dialog = this,
data = {},
iframe = editor.document.createElement( 'iframe' ),
div = editor.document.createElement('div');
this.commitContent( data );
var regex=/^(http:\/\/)vimeo.com\/[0-9]{3,}$/g; //http://vimeo.com/25329849
if(regex.test(data.url)){
var idVideo = data.url.match(/[0-9]{3,}$/g);
data.url = "http://player.vimeo.com/video/" + idVideo;
}
div.setAttribute('class', 'video');
iframe.setAttribute( 'src', data.url + "?byline=0&portrait=0&color=ffffff");
iframe.setAttribute( 'width', '620' );
iframe.setAttribute( 'width', '349' );
iframe.setAttribute( 'frameborder', '0');
div.insertElement(iframe); //problem is here !
editor.insertElement(div);
}
}; });

Found it..
Read the documentation please: docs.ckeditor.com/#!/api/CKEDITOR.dom.element
Elements don't have a insertElement method. This is a method of the editor try this:
iframe.appendTo(div); //problem is solved here!
editor.insertElement(div);
Instead of your previous code:
div.insertElement(iframe); //problem is here !
editor.insertElement(div);

Related

Popup Window is automatically closing after update Browser (IE11 , chrome (newest version)

Hello I am working on a application , where an error has occured after I updated my browsers to the newest version. For example the error doesnt occur if I am using IE 10, with IE 11 the error/bug it is not occuring. I will try the error so exactly as possible. If you cannot follow me, you can ask me explicit questions.
The bug is produced by javascript.
Main Description: I have a button, if it is clicked a popup fenster is opened dynamically with JQuery:
jQuery(html.join('')).dialog(
{
modal : true,
width : 650,
height : 500,
autoOpen : true,
closeOnEscape : true,
draggable : true,
resizable : false,
buttons : [
/*
* { text: alerts_GetMessageText(ghAlertsDetailsMessages,
* 'Alerts.AlertDetails.Reason.Dialog.Cancel') ,click:
* function() { jQuery( this ).dialog( "close" ); }
* ,classes: 'ButtonDialogLeft' },
*/
{
text : alerts_GetMessageText(ghAlertsDetailsMessages,
'Alerts.AlertDetails.Reason.Dialog.OK'),
click : alerts_Details_CloseReasonDialog,
classes : 'ButtonDialogRight'
} ]
});
The bug is, that the Popup-Window is closed immediately after it is shown. I suppose the cause is that the current is redirected to the same current page. So I am landing on the same page with closed popup-window.
I know it is not easy to explain the point, but what is irritating me, that no errors are shown in the console.
The popup window is filled by calling:
goMyAlertsCommandQueue.addAjaxCall({
type : "GET",
url : './showAlertsAlertReasonAjax.do',
dataType : "html",
data : ({
AjaxAction : 'data',
AlertId : alertId
})
}, alerts_Details_OpenReasonDialogReady);
goMyAlertsCommandQueue.run();
alerts_Details_OpenReasonDialogReady is looking like:
function alerts_Details_OpenReasonDialogReady(poHtml) {
// Button ausrichten
/*
* jQuery("button[classes='ButtonDialogLeft']",
* jQuery(this).parent()).css("float","left");
*/
jQuery("button[classes='ButtonDialogRight']", jQuery(this).parent()).css(
"float", "right");
// show dialog data
jQuery("#ReasonDialog div").remove();
jQuery("#ReasonDialog").append(poHtml);
// 'Close'-Button ausblenden
jQuery(".ui-dialog-titlebar-close").show();
dropdownList();
firstTime = false;
}
some time later this function jquery-ui:
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
After return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments ); is being executed, the page is redirected to the current page and the popup is disappearing. No errors are shown in the console. So I cannot recognize what causes the error. If u have any questions so please ask, I am grateful for any help.
Edit: #halcyon
function alerts_Details_OpenReasonDialog() {
var alertId = jQuery(this).attr("alertId");
if (firstTime) {
//
//jQuery("#ReasonDialog").dialog('destroy');
jQuery("#ReasonDialog").remove();
var html = [];
var i = -1;
html[++i] = "<div class='cReasonDialog' id='ReasonDialog' title='"
+ alerts_GetMessageText(ghAlertsDetailsMessages,
'Alerts.AlertDetails.Reason.Dialog.Title') + "'>";
html[++i] = "<div style='margin-top:50px; text-align:center;'>"
+ alerts_GetMessageText(ghAlertsDetailsMessages,
'Alerts.AlertDetails.Reason.Dialog.LoadingData')
+ "</div>";
html[++i] = "<div style='margin-top:25px; text-align:center;'><img src='./reportingErgon/img/icon_loading.gif' alt='"
+ alerts_GetMessageText(ghAlertsDetailsMessages,
'Alerts.AlertDetails.Reason.Dialog.LoadingData')
+ "' /></div>";
html[++i] = "</div>";
jQuery(html.join('')).dialog(
{
modal : true,
width : 650,
height : 500,
autoOpen : true,
closeOnEscape : true,
draggable : true,
resizable : false,
buttons : [
/*
* { text: alerts_GetMessageText(ghAlertsDetailsMessages,
* 'Alerts.AlertDetails.Reason.Dialog.Cancel') ,click:
* function() { jQuery( this ).dialog( "close" ); }
* ,classes: 'ButtonDialogLeft' },
*/
{
text : alerts_GetMessageText(ghAlertsDetailsMessages,
'Alerts.AlertDetails.Reason.Dialog.OK'),
click : alerts_Details_CloseReasonDialog,
classes : 'ButtonDialogRight'
} ]
});
goMyAlertsCommandQueue.reset();
goMyAlertsCommandQueue.addAjaxCall({
type : "GET",
url : './showAlertsAlertReasonAjax.do',
dataType : "html",
data : ({
AjaxAction : 'data',
AlertId : alertId
})
}, alerts_Details_OpenReasonDialogReady);
goMyAlertsCommandQueue.run();
firstTime = false;
} else {
jQuery("#dropdown1 input").val("");
jQuery("#FilterText").val("");
jQuery("#FilterValue").val("");
jQuery("input[name=Rating]:checked").attr("checked", false);
jQuery(".cErrorMessage").text("");
jQuery("#ReasonDialog").dialog('open');
}
}

Custom wp.media with arguments support

How to setup a [add media] button, with:
proper wordpress [media] UI
has size and alignments UI in popup right hand side
can custom popup title and button
size and alignments arguments can send back to be use
Just try to cover most solutions:
use tb_show("", "media-upload.php?type=image&TB_iframe=true"); and window.send_to_editor
problem: has no standard wp.media UI
in js code:
jQuery("#my_button").click(function() {
tb_show("", "media-upload.php?type=image&TB_iframe=true");
return false;
});
window.send_to_editor = function(html) {
console.log(html);
tb_remove();
}
use wp.media({frame: 'post'})
problem: cannot custom UI elements, such as: title, button
in js code:
function clearField(){
#remove file nodes
#...
}
var frame = wp.media({frame: 'post'});
frame.on('close',function() {
var selection = frame.state().get('selection');
if(!selection.length){
clearField();
}
});
frame.on( 'select',function() {
var state = frame.state();
var selection = state.get('selection');
if ( ! selection ) return;
clearField();
selection.each(function(attachment) {
console.log(attachment.attributes);
});
});
frame.open();
use wp.media.editor with wp.media.editor.open( editor_id )
problem: cannot custom UI elements, such as: title, button
in js code: https://wordpress.stackexchange.com/questions/75808/using-wordpress-3-5-media-uploader-in-meta-box#75823
use wp.media with rewrite wp.media.controller.Library and retrieve attachment in select
problem: complicated ..., but once you understand it, it all make sense, and it is my finial solution
in js code:
/**
* Please attach all the code below to a button click event
**/
//create a new Library, base on defaults
//you can put your attributes in
var insertImage = wp.media.controller.Library.extend({
defaults : _.defaults({
id: 'insert-image',
title: 'Insert Image Url',
allowLocalEdits: true,
displaySettings: true,
displayUserSettings: true,
multiple : true,
type : 'image'//audio, video, application/pdf, ... etc
}, wp.media.controller.Library.prototype.defaults )
});
//Setup media frame
var frame = wp.media({
button : { text : 'Select' },
state : 'insert-image',
states : [
new insertImage()
]
});
//on close, if there is no select files, remove all the files already selected in your main frame
frame.on('close',function() {
var selection = frame.state('insert-image').get('selection');
if(!selection.length){
#remove file nodes
#such as: jq("#my_file_group_field").children('div.image_group_row').remove();
#...
}
});
frame.on( 'select',function() {
var state = frame.state('insert-image');
var selection = state.get('selection');
var imageArray = [];
if ( ! selection ) return;
#remove file nodes
#such as: jq("#my_file_group_field").children('div.image_group_row').remove();
#...
//to get right side attachment UI info, such as: size and alignments
//org code from /wp-includes/js/media-editor.js, arround `line 603 -- send: { ... attachment: function( props, attachment ) { ... `
selection.each(function(attachment) {
var display = state.display( attachment ).toJSON();
var obj_attachment = attachment.toJSON()
var caption = obj_attachment.caption, options, html;
// If captions are disabled, clear the caption.
if ( ! wp.media.view.settings.captions )
delete obj_attachment.caption;
display = wp.media.string.props( display, obj_attachment );
options = {
id: obj_attachment.id,
post_content: obj_attachment.description,
post_excerpt: caption
};
if ( display.linkUrl )
options.url = display.linkUrl;
if ( 'image' === obj_attachment.type ) {
html = wp.media.string.image( display );
_.each({
align: 'align',
size: 'image-size',
alt: 'image_alt'
}, function( option, prop ) {
if ( display[ prop ] )
options[ option ] = display[ prop ];
});
} else if ( 'video' === obj_attachment.type ) {
html = wp.media.string.video( display, obj_attachment );
} else if ( 'audio' === obj_attachment.type ) {
html = wp.media.string.audio( display, obj_attachment );
} else {
html = wp.media.string.link( display );
options.post_title = display.title;
}
//attach info to attachment.attributes object
attachment.attributes['nonce'] = wp.media.view.settings.nonce.sendToEditor;
attachment.attributes['attachment'] = options;
attachment.attributes['html'] = html;
attachment.attributes['post_id'] = wp.media.view.settings.post.id;
//do what ever you like to use it
console.log(attachment.attributes);
console.log(attachment.attributes['attachment']);
console.log(attachment.attributes['html']);
});
});
//reset selection in popup, when open the popup
frame.on('open',function() {
var selection = frame.state('insert-image').get('selection');
//remove all the selection first
selection.each(function(image) {
var attachment = wp.media.attachment( image.attributes.id );
attachment.fetch();
selection.remove( attachment ? [ attachment ] : [] );
});
//add back current selection, in here let us assume you attach all the [id] to <div id="my_file_group_field">...<input type="hidden" id="file_1" .../>...<input type="hidden" id="file_2" .../>
jq("#my_file_group_field").find('input[type="hidden"]').each(function(){
var input_id = jq(this);
if( input_id.val() ){
attachment = wp.media.attachment( input_id.val() );
attachment.fetch();
selection.add( attachment ? [ attachment ] : [] );
}
});
});
//now open the popup
frame.open();
I would like to add to ZAC's option 4 because when I used his code, the image src="" was missing.
Here is the fix
if ( 'image' === obj_attachment.type ) {
html = wp.media.string.image( display );
_.each({
align: 'align',
size: 'image-size',
alt: 'image_alt'
}, function( option, prop ) {
if ( display[ prop ] )
options[ option ] = display[ prop ];
});
html = wp.media.string.image( display, obj_attachment );
}
This way you can call the new media uploader with custom title and button and right side bar.
var custom_uploader;
jQuery('#fileform').on('click','.select-files', function(e) {
var button = jQuery(this);
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose File',
library: {
author: userSettings.uid // specific user-posted attachment
},
button: {
text: 'Choose File'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
console.log(attachment.url);
console.log(attachment.id); // use them the way you want
});
//Open the uploader dialog
// Set post id
wp.media.model.settings.post.id = jQuery('#post_ID').val();
custom_uploader.open();
});
Check this link -> https://github.com/phpcodingmaster/WordPress-Media-Modal-Image-Uploads
It will show you how to:
Open the admin media modal
Get single image info
Get multiple images info
Tested with WordPress Version 6.0

Dynamically add UI Elements in CKEditor Dialog

I'm trying to trigger a callback to dynamically populate a CKEditor dialog with checkboxes when the dialog is opened. I've read other solutions that use iframes, but this won't work for me because the dialog needs to be populated based on other elements on the same page.
Here is what I have so far. There are no errors, but the dialog is just empty when it opens. I expect the addContents function to fill in the dialog. I've confirmed that dialog.definition.contents does include the contents and elements that I want, but it's just not filling in the actual dialog. What am I missing?
(function() {
CKEDITOR.plugins.add( 'embeds', {
icons: 'embed',
init: function(editor) {
var self = this,
elements = [];
CKEDITOR.dialog.add('EmbedsDialog', function (instance) {
return {
title : 'Embeds',
minWidth : 550,
minHeight : 200,
contents: [],
onShow: function() {
var dialog = this,
elements = [];
$('#embeds-fields tr').each(function() {
var title = $(this).find('input[type=text]').val(),
url = $(this).find('input[type=url]').val();
if(url != "") {
elements.push({
label : "embed",
title : url,
type : 'checkbox'
});
}
});
dialog.definition.removeContents('embeds');
dialog.definition.addContents({
id : 'embeds',
expand : true,
elements : elements
});
},
}; // return
});
editor.addCommand('Embeds',
new CKEDITOR.dialogCommand('EmbedsDialog', {
allowedContent: 'a[*](*)'
})
);
editor.ui.addButton('Embeds', {
label : 'Embeds',
command : 'Embeds',
toolbar : 'embeds'
});
} // init
}); // add
})(); // closure
Based off of this example, I ended up with this solution, where "main" is the ID of the original content.
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName == 'EmbedsDialog') {
var main = dialogDefinition.getContents('main');
$('#embeds-fields tr').each(function() {
var title = $(this).find('input[type=text]').val(),
url = $(this).find('input[type=url]').val();
if(url != "") {
main.add({
type : 'checkbox',
label : title,
});
}
});
}
});

CKEditor link dialog removing protocol

In my CKEditor I removed the 'linkType' and 'protocol' inputs of the link dialog.
CKEDITOR.on( 'dialogDefinition', function( ev )
{
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' )
{
var infoTab = dialogDefinition.getContents( 'info' );
infoTab.remove( 'linkType' );
infoTab.remove( 'protocol' );
}
});
However, evertype I type in something like https://google.com as soon as I type in the 'g' the https:// gets removed.
I checked the output and it always says http:// disregarding the input.
How can I turn this stupid behaviour off?
After much research, debugging and tweaking, I've finally managed to pull this off!!!
Here's how I do it:
CKEDITOR.on('dialogDefinition', function(e) {
// NOTE: this is an instance of CKEDITOR.dialog.definitionObject
var dd = e.data.definition;
if (e.data.name === 'link') {
dd.minHeight = 30;
// remove the unwanted tabs
dd.removeContents('advanced');
dd.removeContents('target');
dd.removeContents('upload');
// remove all elements from the 'info' tab
var tabInfo = dd.getContents('info');
while (tabInfo.elements.length > 0) {
tabInfo.remove(tabInfo.elements[0].id);
}
// add a simple URL text field
tabInfo.add({
type : 'text',
id : 'urlNew',
label : 'URL',
setup : function(data) {
var value = '';
if (data.url) {
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
} else if (data.email && data.email.address) {
value = 'mailto:' + data.email.address;
}
this.setValue(value);
},
commit : function(data) {
data.url = { protocol: '', url: this.getValue() };
}
});
}
});
Here's how I removed the protocol in v4.5.1:
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName === 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
var url = infoTab.get('url');
url.onKeyUp = function(){};
url.setup = function(data) {
this.allowOnChange = false;
if (data.url) {
var value = '';
if (data.url.protocol) {
value += data.url.protocol;
}
if (data.url.url) {
value += data.url.url;
}
this.setValue(value);
}
this.allowOnChange = true;
};
url.commit = function(data) {
data.url = { protocol: '', url: this.getValue() };
};
}
});
I'm afraid there's no way to change it. You have to manually edit a few lines of the code to make it working your way.
I recently found a way to hide the Link Type so you don't have to remove it totally. Set the style to display: none like the following:
infoTab.get( 'linkType' ).style = 'display: none';
I think it works for the Protocol as well, but I haven't tested it. I answered the same question here
Hope this helps someone!
For the lazy people like me, just do a quick core file hack:
open plugins/link/dialogs/link.js
in the minimized version find d=/^(http|https|ftp|news):\/\/(?=.)/i.exec(b);
remove http|https|ftp|
save file, upload it to your server
If it does not work after reload, this might be a cache problem. Open browser in private mode, navigate to your ckeditor and try it again. Good luck.

How to remove MenuItemTitle from TinyMCE?

I have enabled the 'fontsizeselect' plugin in tinyMCE. My question is how do I remove the header (title) of the drop-down menu?
Edit:
I've tried removing it using JQuery .remove(), but after that the height of whole list is calculated wrong.
The second option I tried was:
http://www.tinymce.com/wiki.php/API3:method.tinymce.ui.DropMenu.remove
But that just went wrong and "fontsizeselect.remove(title)" (analogically to .add) makes error to whole tinyMCE - "missing : after property id". Problably it is completly bad method to do this.
The third option was editing tiny_mce\themes\advanced\editor_template_src.js line 467:
c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) {...}
but seems, that TinyMCE developers thought, that every drop-down must have title/header
SOLVED:
before initialization of MCE we have to override the menu rendering function
(function(tinymce) {
var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef;
tinymce.create('tinymce.ui.ListBoxNoTitle:tinymce.ui.ListBox', {
renderMenu : function() {
var t = this, m;
m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
menu_line : 1,
'class' : t.classPrefix + 'Menu mceNoIcons',
max_width : 250,
max_height : 150
});
m.onHideMenu.add(function() {
t.hideMenu();
t.focus();
});
/* m.add({
title : t.settings.title,
'class' : 'mceMenuItemTitle',
onclick : function() {
if (t.settings.onselect('') !== false)
t.select(''); // Must be runned after
}
});
*/
each(t.items, function(o) {
// No value then treat it as a title
if (o.value === undef) {
m.add({
title : o.title,
role : "option",
'class' : 'mceMenuItemTitle',
onclick : function() {
if (t.settings.onselect('') !== false)
t.select(''); // Must be runned after
}
});
} else {
o.id = DOM.uniqueId();
o.role= "option";
o.onclick = function() {
if (t.settings.onselect(o.value) !== false)
t.select(o.value); // Must be runned after
};
m.add(o);
}
});
t.onRenderMenu.dispatch(t, m);
t.menu = m;
}
});
})(tinymce);
And with this comment on "m.add" You just have to add
tinyMCE.init({
setup : function(ed) {
ed.onBeforeRenderUI.add(function(ed){
ed.controlManager.setControlType('listbox', tinymce.ui.ListBoxNoTitle);
});
}
});
this setup to standard initialization of tinyMCE. So, it can be done without editing source files.

Categories

Resources