How to force CKEditor to process widgets when setting the HTML of an element - ckeditor

I have create a simple CKEditor widget that highlights the elements that have the class "pink".
I have also added a "Pinkify" button to the toolbar, which replaces the HTML of the selected element with some other elements that have the class "pink".
What I observe when I click the button is that widgets are not created for the freshly inserted elements. However, when I toggle between Source mode and WYSISYG mode, the widgets get created.
See the jsfiddle and its code:
CKEDITOR.replace('ck', {
allowedContent: true,
extraPlugins: 'pink'
});
CKEDITOR.plugins.add('pink', {
requires: 'widget',
init: function(editor) {
editor.widgets.add('pinkwidget', {
upcast: function(element) {
return element.hasClass('pink');
}
});
editor.addCommand('pinkify', {
editorFocus: 1,
exec: function(editor) {
var selection = editor.getSelection(),
selectedElement = selection.getStartElement();
if (selectedElement) {
selectedElement.setHtml("Let's have some <span class=\"pink\">pink</span> widget here!");
editor.widgets.checkWidgets(); // needed?
}
}
});
editor.ui.addButton('pinkify', {
label: 'Pinkify',
command: 'pinkify'
});
},
onLoad: function() {
CKEDITOR.addCss('.cke_widget_pinkwidget { background: pink; }');
}
});
I am aware of this question on Stackoverflow, but I can't get it to work with setHtml called on an element. Can you suggest how to modify the code so that widgets get created as soon as the HTML is updated?

According to the CKEditor team, it is normal that CKEDITOR.dom.element.setHtml does not instanciate widgets (see Widgets not initialised after calling setHtml on an element).
So the workaround they gave me was to rewrite the code that insert HTML in place of the selected element to:
if (selectedElement) {
selectedElement.setHtml("");
editor.insertHtml("Let's have some <span class=\"pink\">pink</span> widget here!");
}
For those like me who didn't know, editor.insertHTML inserts HTML code into the currently selected position in the editor in WYSIWYG mode.
Updated jsFiddle here.

Related

CKEditor: multiple widget templates

I'm currently creating a 'smartobject' widget. In the widgets dialog, the user can choose a 'smartobject', which simply put, generates some html, which should be added to the editor. Here comes the tricky part: the html sometimes div elements and sometimes simply span elements. In the case of the div variant, the widget should be wrapped in a div 'template'. In the case of a span variant, the widget should be wrapped in a span and the html should be added 'inline'.
In the widgets API I see the following way to define a template:
editor.widgets.add('smartobject', {
dialog: 'smartobject',
pathName: lang.pathName,
template: '<div class="cke_smartobject"></div>', // <------
upcast: function(element) {
return element.hasClass('smartObject');
},
init: function() {
this.setData('editorHtml', this.element.getOuterHtml());
},
data: function() {
var editorHtml = this.data.editorHtml;
var newElement = new CKEDITOR.dom.element.createFromHtml(editorHtml);
newElement.copyAttributes(this.element);
this.element.setText(newElement.getText());
}
});
But in my case, the template is more dynamic: sometimes a div and sometimes the span will do the correct thing..
How can I fix this without needing to create two widgets which will do the exact same thing, with only the wrapping element as difference?
I've already tried to replace the entire element in the 'data' method, like:
newElement.replace(this.element);
this.element = newElement;
But this seemed not supported: resulted in undefined errors after calling editor.getData().
I'm using ckeditor v4.5.9
Thanks for your help!
It seems I got it working (with a workaround).
The code:
CKEDITOR.dialog.add('smartobject', this.path + 'dialogs/smartobject.js');
editor.widgets.add('smartobject', {
pathName: lang.pathName,
// This template is needed, to activate the widget logic, but does nothing.
// The entire widgets html is defined and created in the dialog.
template: '<div class="cke_smartobject"></div>',
init: function() {
var widget = this;
widget.on('doubleclick', function(evt) {
editor.execCommand('smartobject');
}, null, null, 5);
},
upcast: function(element) {
return element.hasClass('smartObject');
}
});
// Add a custom command, instead of using the default widget command,
// otherwise multiple smartobject variants (div / span / img) are not supported.
editor.addCommand('smartobject', new CKEDITOR.dialogCommand('smartobject'));
editor.ui.addButton && editor.ui.addButton('CreateSmartobject', {
label: lang.toolbar,
command: 'smartobject',
toolbar: 'insert,5',
icon: 'smartobject'
});
And in the dialog, to insert code looks like:
return {
title: lang.title,
minWidth: 300,
minHeight: 80,
onOk: function() {
var element = CKEDITOR.dom.element.createFromHtml(smartobjectEditorHtml);
editor.insertElement(element);
// Trigge the setData method, so the widget html is transformed,
// to an actual widget!
editor.setData(editor.getData());
},
...etc.
UPDATE
I made the 'onOk' method a little bit better: the smartobject element is now selected after the insertion.
onOk: function() {
var element = CKEDITOR.dom.element.createFromHtml(smartobjectEditorHtml);
var elementId = "ckeditor-element-" + element.getUniqueId();
element.setAttribute("id", elementId);
editor.insertElement(element);
// Trigger the setData method, so the widget html is transformed,
// to an actual widget!
editor.setData(editor.getData());
// Get the element 'fresh' by it's ID, because the setData method,
// makes the element change into a widget, and thats the element which should be selected,
// after adding.
var refreshedElement = CKEDITOR.document.getById(elementId);
var widgetWrapperElement = CKEDITOR.document.getById(elementId).getParent();
// Better safe then sorry: if the fresh element doesn't have a parent, simply select the element itself.
var elementToSelect = widgetWrapperElement != null ? widgetWrapperElement : refreshedElement;
// Normally the 'insertElement' makes sure the inserted element is selected,
// but because we call the setData method (to ensure the element is transformed to a widget)
// the selection is cleared and the cursor points to the start of the editor.
editor.getSelection().selectElement(elementToSelect);
},
So in short, I partially used the widget API for the parts I wanted:
- Make the html of the widget not editable
- Make it moveable
But I created a custom dialog command, which simply bypasses the default widget insertion, so I can entirely decide my own html structure for the widget.
All seems to work like this.
Any suggestions, to make it better are appreciated:)!
As suggested in this ckeditor forum thread, the best approach would be to set the template to include all possible content elements. Then, in the data function, remove the unnecessary parts according to your specific logic.

CKEditor not editable in IE11 after ajax call

Example:
Jsfiddle
If the page is loaded the first time, the CKEditor is working right and the value of the editor can be edited. After hitting the button "ajax" which is calling the following function (cursor must be in the editor field):
function ajax_call() {
var html = "<textarea id=\"textarea\"><p>test 1</p><p>test 2</p><p>test 3</p></textarea><script type='text/javascript'>jQuery(document).ready(function() { ckEditor('textarea'); });<\/script>";
$.post("/echo/html/", { html: html }, function(data){
jQuery('#target').html(data);
});
}
it isn't possible to click on the text in IE11 to edit the value. Clicking beyond the text or left of it enabels the editor again.
Looks like creation of new textarea after CKEDITOR is initiated brakes editor in IE. Though i just tried to set data directly on instance of CKEDITOR and it worked fine,rather than creating new textarea tag.
function ajax_call() {
var html = "<p>test 4</p><p>test 5</p><p>test 6</p>";
$.post("/echo/html/", { html: html }, function(data){
//jQuery('#target').html(data); <-- Removed from original
CKEDITOR.instances['textarea'].setData(data)// <-- Added
});
}
function ckEditor(id) {
CKEDITOR.replace(id, {
language : 'de',
});
}
jQuery(document).ready(function() {
ckEditor('textarea');
});
Here is working example:
http://jsfiddle.net/2wq86gqs/15/

How to add Toolbar Button for Firefox Australis

I used below code to add toolbar buttons automatically in navigation toolbar below Firefox Australis.
var buttonId = "toolbarbutton-toolbarbutton";
var navBar = document.getElementById("nav-bar");
var currentSet = navBar.currentSet;
var curSet = currentSet.split(",");
if (curSet.indexOf(buttonId) == -1)
{
navBar.insertItem(buttonId);
navBar.setAttribute("currentset", navBar.currentSet);
document.persist("nav-bar", "currentset");
try
{
top.BrowserToolboxCustomizeDone(true);
}
catch (e)
{
}
}
Because user interface and modules changed for Australis, the code needs to be updated. How can I add Toolbar Button for Australis proper way?
You have to use the CustomizableUI module:
try
{
Components.utils.import("resource:///modules/CustomizableUI.jsm");
CustomizableUI.createWidget({
id: "toolbarbutton-toolbarbutton",
defaultArea: "nav-bar",
removable: true,
label: "My button",
tooltiptext: "My tooltip text",
onClick: function()
{
alert("Clicked");
}
});
}
catch (e)
{
Components.utils.reportError(e);
// No such module? Try the old approach.
...
}
Note that the widget no longer needs to be added for each browser window, it is enough to do it once. Unfortunately, the module documentation is practically non-existent right now, the code above has been deduced from module's source code. The documentation should improve soon however.
If it helps, Adblock Plus source code contains an emulation of the CustomizableUI API for older Firefox versions. This one is far from complete however, it is only meant to cover the needs of Adblock Plus.

CKEDITOR - how to add permanent onclick event?

I am looking for a way to make the CKEDITOR wysiwyg content interactive. This means for example adding some onclick events to the specific elements. I can do something like this:
CKEDITOR.instances['editor1'].document.getById('someid').setAttribute('onclick','alert("blabla")');
After processing this action it works nice. But consequently if I change the mode to source-mode and then return to wysiwyg-mode, the javascript won't run. The onclick action is still visible in the source-mode, but is not rendered inside the textarea element.
However, it is interesting, that this works fine everytime:
CKEDITOR.instances['editor1'].document.getById('id1').setAttribute('style','cursor: pointer;');
And it is also not rendered inside the textarea element! How is it possible? What is the best way to work with onclick and onmouse events of CKEDITOR content elements?
I tried manually write this by the source-mode:
<html>
<head>
<title></title>
</head>
<body>
<p>
This is some <strong id="id1" onclick="alert('blabla');" style="cursor: pointer;">sample text</strong>. You are using CKEditor.</p>
</body>
</html>
And the Javascript (onclick action) does not work. Any ideas?
Thanks a lot!
My final solution:
editor.on('contentDom', function() {
var elements = editor.document.getElementsByTag('span');
for (var i = 0, c = elements.count(); i < c; i++) {
var e = new CKEDITOR.dom.element(elements.$.item(i));
if (hasSemanticAttribute(e)) {
// leve tlacitko mysi - obsluha
e.on('click', function() {
if (this.getAttribute('class') === marked) {
if (editor.document.$.getElementsByClassName(marked_unique).length > 0) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked_unique);
}
} else if (this.getAttribute('class') === marked_unique) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked);
}
});
}
}
});
Filtering (only CKEditor >=4.1)
This attribute is removed because CKEditor does not allow it. This filtering system is called Advanced Content Filter and you can read about it here:
http://ckeditor.com/blog/Upgrading-to-CKEditor-4.1
http://ckeditor.com/blog/CKEditor-4.1-Released
Advanced Content Filter guide
In short - you need to configure editor to allow onclick attributes on some elements. For example:
CKEDITOR.replace( 'editor1', {
extraAllowedContent: 'strong[onclick]'
} );
Read more here: config.extraAllowedContent.
on* attributes inside CKEditor
CKEditor encodes on* attributes when loading content so they are not breaking editing features. For example, onmouseout becomes data-cke-pa-onmouseout inside editor and then, when getting data from editor, this attributes is decoded.
There's no configuration option for this, because it wouldn't make sense.
Note: As you're setting attribute for element inside editor's editable element, you should set it to the protected format:
element.setAttribute( 'data-cke-pa-onclick', 'alert("blabla")' );
Clickable elements in CKEditor
If you want to observe click events in editor, then this is the correct solution:
editor.on( 'contentDom', function() {
var element = editor.document.getById( 'foo' );
editor.editable().attachListener( element, 'click', function( evt ) {
// ...
// Get the event target (needed for events delegation).
evt.data.getTarget();
} );
} );
Check the documentation for editor#contentDom event which is very important in such cases.

Why cannot create icons dynamically in ajax?

Normally, when I write the followings:
<a id="sta_numberOfIcons" class="icon-user" rel="popover"></a>
And js:
$("a[rel=popover]").each(function(){
$(this).popover({
trigger: 'hover',
placement: 'top',
html: true,
title:"Passenger Info",
content: "content "+$(this).attr('id')
})
.click(function(e) {
e.preventDefault()
});
});
It works and I can see a popover for the icon.But when I write the following code,to create the icons dynamically, but I cannot show popovers for the newly created icons.
html part:
Stations:
<select name="selectStation" id="selectStation" onchange="sta_callStation(this);"></select>
<a id="sta_numberOfIcons" class="icon-user" rel="popover"></a>
<div id="infoOfPassengers"></div>
<div id="distType"></div>
<div id="distParams"></div>
In Stations combobox, options are filled when the page is loaded.They are filled normally.
js function for getting the number of passengers from php, and create icons accordingly:
function sta_callStation(sel){
$('#noOfPassengers, #infoOfPassengers, #distType,#distParams').empty();
$('#sta_numberOfIcons').empty();
$.getJSON('Stations.php', function(station){
$.each(station, function(sta_key, sta_value) {
if(sel.value==sta_key)
{
$.each(sta_value.passengers, function(j,passengers)
{
var pas_icon = document.createElement("a");
pas_icon.className ='icon-user';
pas_icon.id='id_'+j;
pas_icon.setAttribute('href', '#');
pas_icon.setAttribute('rel', 'popover');
//alert('id_'+(j));
var empty=document.createElement("a");
empty.appendChild(document.createTextNode(" "));
document.getElementById('sta_numberOfIcons').appendChild(pas_icon);
document.getElementById('sta_numberOfIcons').appendChild(empty);
});
}
});
});
}
The icons appear in the page under the combobox.I just put to try, I don't know how to insert the new created icons to a tag.I just appended the newly created icons to tag.What is wrong here?Why I cannot show popovers for the created icons?Please help.
The JS code that you have which successfully wires-up the popover for elements $("a[rel=popover]") needs to execute after you have dynamically added your icons.
You could paste those lines into the end of the logic in sta_callStation() but it is probably better to put them into their own function and call that from sta_callStation().
Something like:
function bindMyPopovers() {
$("a[rel=popover]").each(function(){
$(this).popover({
trigger: 'hover',
placement: 'top',
html: true,
title:"Passenger Info",
content: "content "+$(this).attr('id')
})
.click(function(e) {
e.preventDefault()
});
});
}

Resources