1. CKEditor4 installation
Installing CKEditor is easy. Select the appropriate process (new installation or upgrade) and install it as described below.
1. New installation
The first time to install CKEditor, proceed as follows:
1) Download the latest version of CKEditor from the CKEditor website: /download.
2) Unzip the downloaded document into the ckeditor directory in the root directory of your website. You can place the document in any path to your website. The ckeditor directory is the default directory.
2. Upgrade
To upgrade an existing CKEditor installation, proceed as follows:
1) Rename your old edit folder to a backup folder, such as ckeditor_old.
2) Download the latest version of CKEditor from the CKEditor website: /download.
3) Unzip the downloaded document to the original editor directory, such as ckeditor.
4) Copy the configuration file you have changed from the backup directory to the corresponding location of its new directory. These configuration files
The following documents may include (but are not limited to):
,
,
3. Verify the installation
CKEditor comes with a sample page, which can be used to verify that the installation is normal. To see if the editor works, look at the sample directory.
To check the installation, call the following page in your site:
http://<your site>/<CKEditor installation path>/samples/
For example: /ckeditor/samples/
2. Integration
1. Load CKEditor
CKEditor is a JavaScript application. To load it, you need to include a simple file reference in the page. If you have installed CKEditor in the ckeditor directory under the root directory of the site, you need to insert the following code snippet into the <head> part of the page:
<head> ...<script src="/ckeditor/"></script></head>
When the above file is loaded, you can use the CKEditor JavaScript API.
When adding CKEditor to a web page, the original filename() is used. If you want to use a different file name, or even want to merge CKEditor into another JavaScript file, please refer to the Specifying the Editor Path section in the developer's guide first.
Generate editor
Now you can use the CKEditor JavaScript API in the page, and you can use it to generate an editor. To do this, there are two options available:
1. Framed Editing
The most commonly used way of using it is to place the toolbar and editing area in the specified location on the page.
2. Inline Editing
Used in the page that looks like the final one. Editing can be applied directly to HTML elements through the contenteditable property of HTML5. Click on the option you prefer to get more information.
3. Framed Editing
Framework editing is the most commonly used method to use CKEditor. Its usual manifestation is to place toolbars and editing areas in specified locations in the page.
After loading the CKEditor script, you can prepare to generate the editor.
2. Generate frame-based editing
When editing in frames, CKEditor works like a text field element in a page. The editor provides a user interface that can be easily written, formatted, and processed with rich text, but the same thing can be done with the <textarea> element (although not so easy), requiring the user to enter HTML code in it.
In fact, CKEditor uses text fields to pass its data to the server. For terminal use, the text field is invisible. In order to generate an instance of the editor, the <textarea> element must first be added to the source code of the HTML page.
<textarea name="editor1"><p>Initial value.</p></textarea>
Note that if you want to load data into the editor, such as from the data, you need to place the data into the <textarea> element, just like the HTML-encoded <p> element in the above example.
In this example, the text field is named editor1. After receiving the submitted data, this name can be used in the server-side code
After inserting the text field, you can use the CKEditor JavaScript API to replace the HTML element with an instance of the editor. To do this, a simple method needs to be called:
<script>( 'editor1' );</script>
This script block must be included anywhere in the page source code after the <textarea> tag.
You can also call the replace function in the <head> section, but you need to listen to the event at this time:
<script> = function() {( 'editor1' ); };</script>
Save editor data
As mentioned above, the editor works similarly to the <textarea> domain. This means that when submitting a form containing an editor instance, the data will be submitted very simply, using the <textarea> element name as the key to check it.
For example, following the above example, we can generate the following PHP code:
<?php $editor_data = $_POST[ 'editor1' ];?>
Client data processing
Some applications (such as Ajax-based) need to process all the data on the client and send the data to the server in their specific methods. If so, using the CKEditor JavaScript API is enough to easily retrieve data from the editor instance. To do this, you can use the getData method:
<script>var editor_data = .(); </script>
Complete example
To insert a CKEditor instance, you can use the following example to generate a page that contains a form that was replaced with CKEditor.
<html> <head> <title>CKEditor Sample</title> <script src="/ckeditor/"></script> </head> <body> <form method="post"> <p> My Editor:<br> <textarea name="editor1"><p>Initial value.</p></textarea> <script> ( 'editor1' ); </script> </p> <p> <input type="submit"> </p> </form> </body> </html>
3. Inline Editing
Inline editing is a new technology that allows you to edit pages that look like the final look. It is a complete "what you see is what you get" (WYSIWYG) experience because not only the edited content looks like the final look, but the page and context in which the content resides.
Enable inline editing
Inline editing can be enabled directly on HTML elements through HTML5's contenteditable property.
For example, suppose you want to use a <div> element to edit. You can do this:
<div contenteditable="true"> <h1>Inline Editing in Action!</h1> <p>The div element that holds this text is now editable. </div>
Editing can also be enabled through code, by calling:
<div contenteditable="true"> <h1>Inline Editing in Action!</h1> <p>The div element that holds this text is now editable.</p> </div> <script> // Turn off automatic editor creation first. = true; ( 'editable' ); </script>
When clicking in the above <div> content, the toolbar of CKEditor appears.
Retrieve editor data
Unlike frame-based editing, when using inline editing, the data edited with CKEditor is not placed in <textarea>, but is directly present in the DOM of the page. Therefore, the application needs to complete the operations required to check data and store it.
To check the editor's data, simply call the editor instance's method. For the above example, as follows:
<script> var data = (); // Your code to save "data", usually though Ajax. </script>
Note that in order to retrieve the editor instance, the original <div> id has been passed to the object.
3. Configuration
1. Set the configuration of CKEditor
CKEditor has a rich set of configuration options that can customize its appearance, functionality, and behavior. The main configuration file name is. This file can be found in the root directory of the CKEditor installation folder.
Available configuration options
All available configuration options can be found in the API documentation. Reference object definition.
Define configuration in page (In-Page)
The best way to set up a CKEditor is to set it in the page when an editor instance is generated. This method allows you to avoid modifying the files originally published in the CKEditor installation folder, making the upgrade task easier.
In the page, the settings can be passed to any editor instance to generate functions, i.e., and. For example:
( 'editor1', { toolbar : 'Basic', uiColor : '#9AB8F3' });
Note that configuration options are passed through a literal object definition (starting with the '{'" symbol and ending with the '}' symbol). Therefore, the correct syntax for each option is ("Configuration Name"): ("Configuration Value"). Be sure not to use the "equal" character (=) at the colon character (:).
Use files
You can also configure the settings of CKEditor by using files. This file is almost empty by default. To change the configuration of CKEditor, add the settings you want to modify to the file. For example:
= function( config ) { = 'fr'; = '#AADC6E'; };
In order to apply configuration settings, functions must always be defined. The file will be executed within the page scope, so you can also reference variables defined in the page (In-Page) or even other JavaScript files.
Use custom configuration files
Using a customized configuration file is another recommended way to set up CKEditor configuration. Without using the default file, you can copy this file anywhere on the site and simply boot the editor to load it. The advantage of this method is that using this method can avoid changing the original files, making it easier to upgrade CKEditor later, just simply overwrite all files.
Suppose you copy the file to a folder called custom in the root directory of your site. You also renamed this file to ckeditor_config.js. At this point, to use custom settings defined in the file, just set the customConfig configuration options when generating the editor instance. For example:
( 'editor1', { customConfig : '/custom/ckeditor_config.js' });
Custom configuration files must look like default files.
The loading order of configuration
You are not required to use only one of the above configuration options. The above methods can be mixed and the configuration can be loaded correctly. The following list shows the configuration loading order used when generating the editor instance:
-
Generate an instance of the editor. At this point, all its configuration items are set to missing values.
-
If there are configuration settings in the page (in-page), the file is loaded, otherwise the default file is loaded. All settings in the custom configuration file override the configuration of the current instance.
-
If a new customConfig value is also defined in the settings loaded in the second step, another configuration file is loaded and its settings override the current settings of the instance. Recursive to all files until customConfig is not defined again.
-
Finally, the settings defined in the page (in-page) override the current settings of the instance (except customConfig, which has been used in the first step).
Avoid loading external settings files
It is also possible to completely avoid loading external configuration files to reduce the number of files loaded. To do this, you need to
Set to an empty string. For example:
( 'editor1', { customConfig : ' ' });
If you do not have configuration in the file and do not have a customized configuration file, this setting must be recommended.
2. Customization of toolbar
Although CKEditor is a fully-featured "what to see is what to get" editor, not all of its options are required in all cases. Therefore, toolbar customization is one of the most commonly used requirements.
There are two ways to configure the toolbar to match requirements:
-
Toolbar group configuration
-
"Organization" configuration
Toolbar group configuration
CKEditor 4 introduces a new concept to the organization toolbar, which is based on "grouping" rather than the traditional "item-by-item positioning" approach.
Configuration grouping is defined by toolbarGroups settings. The following is the configuration used for the release of the CKEditor standard:
= [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ];
It is a list of objects (arrays) with each item having a "name" (such as "clipboard" or "links") and an optional "subgroup" list.
Change the order of groups
By changing the above configuration, the order and position of the groups can be easily customized.
By adding '/', as seen above, you can force a row-break in the toolbar.
Note: In the above configuration, are there any groups used. This is because of "design" (see "The Benefits of Group Configuration").
Benefits of group configuration
The most important benefit of configuring toolbar grouping compared to "item-by-item" configuration is: automation.
Now let the plugin developer decide which group their plugin should add buttons to the toolbar. For example, the Image plug-in can include its buttons into the Insert group, and the Undo and Redo buttons are added to the Undo subgroup.
Although not mandatory, it is recommended to configure all groups and subgroups (including those that are not used), because at any time in the future, when a new plug-in is installed, its buttons will automatically appear in the toolbar without any further configuration.
Disadvantages of group configuration
The most obvious problem with grouping configuration is the inability to precisely control where each item is placed in the toolbar. It is determined by the plugin itself.
"Organization" configuration
In addition to grouping configuration, you can also control each individual element in the toolbar by determining the exact location. This is done by configuring the Toolbar Definition.
A toolbar definition is a JavaScript array that contains elements that can be used in the editor to display in all toolbar lines. Here is an example:
= [ { name: 'document', items: [ 'Source', '-', 'NewPage', 'Preview', '-', 'Templates' ] }, { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] }, '/', { name: 'basicstyles', items: [ 'Bold', 'Italic' ] } ];
Here each toolbar group is given a name and defines an exact list of items in it. You can also implement the above in a simple syntax (see "Access Questions" later):
= [ [ 'Source', '-', 'NewPage', 'Preview', '-', 'Templates' ], [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ], '/', [ 'Bold', 'Italic' ] ];
Include the project separator in it by adding '-' (short line) to the project list, as seen above.
Add '/' between groups to force a line break in the toolbar. They can be used to force a row break at the location where they are placed so that the next toolbar group is in the new row.
Benefits of “item-by-item” configuration
The most obvious benefit of this configuration is that the position of each individual item in the toolbar is controllable.
Disadvantages of "item-by-item" configuration
The biggest problem is that there is no automation when installing new plugins. This means that if any new plugins are added to your editor, you will have to manually change your configuration to include the plugin buttons where you want it.
Accessibility issues
The names used for each toolbar group will be used by help technologies such as screen readers. This name will be used by CKEditor to find the "readable" name of each toolbar group in the editor language file (toolbar group entry).
The screen reader will display each toolbar group by using its readable name (if available) or its defined name properties.
3. Style
The Stryles Combo plugin adds a combination to the CKEditor toolbar and contains a style list. This list makes it easy to apply customized styles and semantic values to content generated in the editor.
It is easy to customize the entries available in the combination drop-down list to suit your needs.
Define styles
A style definition is a JavaScript array that is registered by calling a function. The style definition must be assigned a unique name so that each editor instance can be configured to load it later. This method can make a style definition share by multiple CKEditor instances in the page.
The following code shows how to register an example style definition.
( 'my_styles', [ // Block-level styles { name: 'Blue Title', element: 'h2', styles: { 'color': 'Blue' } }, { name: 'Red Title' , element: 'h3', styles: { 'color': 'Red' } }, // Inline styles { name: 'CSS Style', element: 'span', attributes: { 'class': 'my_style' } }, { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } } ]);
The style definition registration as shown above can be built into the page source code, or exist in an external file, loading "on demand" whenever needed. (See below).
When you are ready to define, you must use stylesSet to make the editor apply the newly registered style by using stylesSet. This can be set in the file, for example:
= 'my_styles';
Defining files using external styles
You can include style-defined registration calls in an external JavaScript file. By default, CKEditor loads style definitions from files in its installation folder.
Your style definition file can be saved anywhere on the site (or somewhere on the internet). However, you have to know the URL you need to access it. For example, you can save this file in the root directory of your site, press / to call it, or place it anywhere else and reference it with its full URL, such as /.
At this point, change the stylesSet settings so that the editor points to this file:
= 'my_styles:/'; //or = 'my_styles:/';
The syntax for style definition settings is always: style definition name: file URL.
Note that a unique name used when registering the style definition in this file must be used.
Style rules
The input item in the style definition is called "Style Rules". Each rule defines the display name and elements, attributes of a single style, and the CSS style used. Here is its general manifestation:
{ name: 'Name displayed in the Styles drop-down list', element: 'HTML element name (for example "span")', styles: { 'css-style1': 'desired value', 'css-style2': 'desired value', ... } attributes: { 'attribute-name1': 'desired value', 'attribute-name2': 'desired value', ... } }
Name and element values are required, while other values are optional.
Types of styles
There are three style types, each related to the elements used in the style rules:
-
Block-level styles - applied as a whole to text blocks (paragraphs), not limited to text selection. Applied to the following elements: address, div, h1, h2, h3, h4, h5, h6, p, and pre.
-
Object styles - Used for special selectable objects (not textual), no matter whenever your browser supports such selection. Applied to the following elements: a, embed, hr, img, li, object, ol, table, td, tr and ul.
-
Inline styles - Applied to text selection, the elements used by their style rules are not defined in other style types.
Stylesheet Parser Plugin
Another simplified approach exists to customize the styles that generate documents in CKEditor, populating the drop-down list with style definitions added in the external CSS style single file.
The Style Single Parser Plugin allows the use of existing CSS styles without having to define styles specifically for CKEditor in the format given above.
After installing the style single parser, you need to use the contentsCss configuration settings to provide the location of the CSS file containing the style definition:
Finally, if you want to skip loading the default styles used by CKEditor, you can set stylesSet to a null value:
= 'sample_CSS_file.css';
This workaround allows the editor to use existing CSS style single rules without generating separate style definitions for CKEditor. On the other hand, the previously used methods provide more control over the user's styles to use, so the two methods can be used interchangeably as needed.
Select CSS selector
This plugin can be fine-tuned to consider only CSS selectors that match the stylesheetParser_validSelectors configuration value. The default regular expression accepts all CSS rules of the form, but it can be modified to reference a limited set of elements, as in the following example:
// Only add rules for <p> and <span> elements. (Add rules only for <p> and <span> elements config.stylesheetParser_validSelectors = /\^(p|span)\.\w+/;
Limit CSS selectors
Customization can also be done by setting the configuration value of stylesheetParser_skipSelectors. Then, the plugin will struggle to ignore CSS rules that match regular expressions, will not display them in the drop-down list, nor will it use them to output document content. The default value does not include all elements of <body> and classes defined for non-specific elements, but it can be modified to ignore a wider set of elements, as shown in the following example:
// Ignore rules for <body> and <caption> elements, classes starting with "high", and any class defined for no specific element. (Ignore rules for <body> and <caption> elements, classes starting with "high", and classes defined for non-specific elements)config.stylesheetParser_skipSelectors = /(^body\.|^caption\.|\.high|^\.)/i;
4. Advanced content filter
introduce
Note: Advanced content filters were introduced in CKEditor 4.1.
What is Advanced Content Filter (ACF)?
ACF is a highly configurable CKEditor core feature available from CKEditor 4.1. It limits and adapts input data (HTML code added in source code mode or by method, pasted HTML code, etc.), so it can configure the editor's configuration in a more feasible way. It can also invalidate the ability to generate HTML code that is not allowed by configuration.
Advanced content filters have two working modes:
1. Automatic mode - The obsessiver is configured by editor functions (such as plug-ins, buttons and commands). These functions are matched by
Set options such as, and to enable.
2. Custom mode - The filter is configured by the options, and only the functions that match this setting are activated.
In both modes, the configuration of the filter can be extended by using settings.
If you want the Advanced Content Filter not working, set to "true". All available editor features will be activated and the input data will not be filtered.
Automatic mode
The Advanced Content Filter operates in automatic mode when no settings are provided. When the editor is initialized, the editing function adds its rules to the filter. Therefore, only content that can be edited using the currently loaded function is allowed, and everything else is filtered out.
The following examples may make it easier to understand the automatic mode of ACF.
1. Open the example from the full or standard CKEditor package (the feature set provided by the base package is too limited).
2. Check editor 1. It uses the default configuration, so all available buttons, keys, or styles in the package are valid
, and the editor content is the same as the initial load (except for the small details in the standard package - because the standard package does not include the Justify plugin, the footer is not aligned to the right).
3. Now check editor 4. You can see that many plugins and buttons have been removed and the .format_tags list has also been reduced. The configuration changes are automatically reflected in the editor's content--the Image toolbar button is gone, so there is no image in the content; the Table plug-in is gone, so the table added to the original content is also removed. You can see in source code mode how the editor clears pasted content or HTML code.
If you want to configure the editor to work in automatic mode, but need additional HTML tags, properties, styles, or classes to take effect, you can use the configuration options.
Custom mode
When the settings are defined, the Advanced Content Filter works in custom mode. This configuration option tells the filter which HTML elements, attributes, styles, and classes are allowed. Based on the default rules (called Allowed Content Rules), the editor filters the input data to determine which functions take effect.
Allowed Content Rules can be set to two different formats: compact string format and more powerful object format. For the allowed content rules, please read the allowed content rules.
The following examples can make it easier to understand the custom mode of ACF.
1. Open the example from the full or standard CKEditor package (the feature set provided by the base package is too limited).
2. Check editor 1. It uses the default configuration, so all available buttons, keys, or styles in the package are valid, and the editor's content is the same as what was originally loaded (except for the small details in the standard package - because the standard package does not include the Justify plugin, and the footer is not aligned to the right).
3. Check editor 2. Options define the allowable content rules to use string format. Note that because these rules do not allow the 's' element, the Strike Through button is deleted from the toolbar, and the deletion formatting in the text is also deleted. The same is true for examples with Horizontal Line, Subscript and Superscript functions.
Take a look at the Styles and Format drop-down lists, which only contain items defined in the allowable content rules. Moreover, the options available in some dialogs are also limited. For example, the image dialog window only contains URL, Alternative Text, width and height values, because only these properties are defined in it.
4. In addition, editor 3 is configured to use different rule sets defined using object format.
Content Transformations
Advanced content filters not only remove unauthorized HTML elements, their classes, styles, and attributes, but also try to uniformly input data by converting elements from one form to another preferable form.
Consider the Bold function. In HTML code, it can be represented by <strong>, <b>, or even <span style="font-weight:700|800|900|bold"> elements. Assume that the settings contain only the rules for <b>. Does this mean that when parsing <string> or <span> elements, they are deleted?
Won't. The editor will convert them all into <b> elements. The result is that the editor will only contain <b> elements and will retain the visual form of pasted content. The same is true if the default value is retained (in automatic mode) - all bold functional forms will be unified into preferred forms.
Suppose that the 'img[!src,alt,width,height]' setting (the <img> tag with the required src and three optional properties) is added to the allowable content rule. Image size should be set with properties, so, as an example, pasted images with style size will be converted to images with properties (note that not all cases are possible - only pixel-based sizes can be converted).
The content conversion function is completely automatic and does not require configuring it. The only thing you need to do is set options, or use the default value (auto mode)
Currently, we have only defined content conversions for several editor functions, but the number will increase in future releases.
Allowed Content Rules
Note: Advanced content filters were introduced in CKEditor 4.1.
Introduction
The allow content rule defines which HTML elements, attributes, styles, and classes are allowed. When configuring CKEditor, you will be most interested in setting options. Plugin developers also need to set properties to tell the editor what a feature allows in automatic mode.
The allowable content rules usually include four main parts:
-
Allowed elements,
-
The attributes that these elements can have,
-
The styles these elements can have,
-
These elements can have classes.
Note: Instead of writing "attributes", styles, and classes", use "properties" as a simple description method.
There can be multiple rules for an element, and an element can be included in a list of multiple elements. For example, each rule may allow another element attribute set.
Rules are applied one by one. Initially, the filtered element is invalid and all its attributes are rejected. The first rule applied to the element verifies it (it will not be deleted), and the rule may accept properties of certain elements. Another rule may make the editor accept more element attributes. therefore:
-
If an element does not have a rule, delete it.
-
It may accept an element, but reject all its properties, and then it is deleted.
-
Once verified, an element and its attributes cannot be invalidated by another rule.
String Format
String format is a compact notation that allows content rules, but it does not provide all the features available in object formats. However, in most cases, it should be enough.
Rule format:
elements [attributes]{styles}(classes)
Regular expression template:
<elements><styles, attributes, and classes><separator> /^([a-z0-9*\s]+)((?:\s*\{[!\w\-,\s\*]+\}\s*|\s*\[[!\w\-,\s\*]+\]\s*|\s*\([!\w\-,\s\*]+\)\s*){0,3})(?:;\s*|$)/i,
in:
-
elements – A column of element names or an asterisk (*) characters separated by spaces,
-
attributes – a comma-separated attribute name or an asterisk (*) character,
-
styles – a comma-separated style name or an asterisk (*) character,
-
classes – a comma-separated class or an asterisk (*) character,
Special characters:
-
The asterisk used in the element list means: "The rule accepts the following attributes to all elements, but not the elements themselves; there must be another rule that explicitly accepts these elements".
-
The asterisk in the attribute list means: "Accept all attributes".
-
The exclamation mark (!) (such as [!href]) used before the entry name in the attribute list means: "This attribute is required.
If an element does not have this property, this rule should not be applied to that element (so this element will not be verified by it).
example:
// A rule accepts <p> and <h1> elements, but does not have any attributes. p h1 //A rule accepts <p> and <h1> elements with optional "left" and "right" classes // Note: Both elements may contain these classes, not just <h1>p h1(left,right) //A rule accepts <p> and <h1> elements with all its attributesp h1[*] //A rule accepts <a> only if it contains the "href" attribute. a[!href] //A rule accepts <img>, which has the required "src" attribute and an optional "alt" attribute, plus optional "width" and "height" stylesimg[alt,!src]{width,height} //Same as above, because the order of properties and their manifest are not related, and spaces are ignoredimg { height, width } [ !src, alt ]
The allowable content rule set can contain multiple rules separated by a semicolon (;). like:
// These rules allow:// <p and ><h1> elements with optional "text-align" styles // <a> with required "href" attributes// <strong> and <em> elements,//<p> with optional "tip" class (so <p> elements can have both "text-align" style and "tip" class) p h1{text-align}; a[!href]; strong em; p(tip) //These rules allow:// <p> and <h1> elements with optional "id" attributes//<a> with the required "href" attribute and optional "id" attributep h1; a[!href]; *[id]
debug
To verify that the allowed content rules are parsed correctly, the properties of the object can be checked.
var editor = ( 'textarea_id', { allowedContent: 'a[!href]; ul; li{text-align}(someclass)' } ); ( 'instanceReady', function() { ( ) } ); // This will log the following array:// { elements: 'p br', ... } (default editor rules)// { elements: 'a', attributes: '!href' } // { elements: 'ul' } // { elements: 'li', styles: 'text-align', classes: 'someclass' }
Object Format
For ease of use, the content rules are allowed to be defined as standard object literals, so the following:
allowedContent: 'p h1{text-align}; a[!href]; strong em; p(tip)' // Corresponding to the following: allowedContent: { 'p h1': { styles: 'text-align' }, a: { attributes: '!href' }, 'strong em': true, p: { classes: 'tip' } }
Using this method, the content rules can be dynamically generated by JavaScript and stored in JSON data format for any purpose. Note: The keys for the object literal must be unique, so:
allowedContent: { p: { styles: 'text-align' }, p: { classes: 'tip' } } //Equivalent to:allowedContent: 'p(tip)' //But it will never be:allowedContent: 'p{text-align}(tip)'
5. Output Formatting
CKEditor provides a powerful and flexible output formatting system. It gives developers full control over how HTML code generated by the editor looks like. This system can control all HTML tags and can give different results for each tag.
HTML Writer (HTML Writer)
HTML writer plugin allows CKEditor to generate advanced formatted output.
The class uses "writer" to write output data. Therefore, the current writer for a specific editor instance can be retrieved using properties.
Several output formatting options can be configured by setting the writer property. The following example summarizes the most commonly used types and gives their default values:
var writer = ; // Generate a string used for indentation progress = '\t'; //The way of the self-end mark is like<br /> = ' />';// The string used to break the line = '\n';// Rules for writing tags ( 'p', { // Indicates indentation when this flag interrupts the line indent: true, //Insert line breaking before the start mark of <p> breakBeforeOpen: true, //Insert line breaking after the start mark of <p> breakAfterOpen: true, // Insert line breaking before the end tag of <p> breakBeforeClose: false, // Insert line breaking after the end tag of <p> breakAfterClose: true });
Set writer rules
Because the editor is a property of each editor instance, and because of the dependency on the loaded writer plugin, the best way to modify it is to listen for events; this means it is safe to assume that the property will be loaded and ready to be modified. The following code shows an example of using this method when generating an editor instance:
( 'editor1', { on: { instanceReady: function( ev ) { // Output paragraphs as <p>Text</p>. ( 'p', { indent: false, breakBeforeOpen: true, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: true }); } } });
Another way is to use the CKEDITOR object so that all editor instances will be changed:
( 'instanceReady', function( ev ) { // Ends self closing tags the HTML4 way, like <br>. = '>'; });
6. Spell Checking
CKEditor can be configured to use the spell checking function locally provided by the browser, or can also use an external spell checking web service.
Local spell checker
The local spell checking function is disabled in the editor by default. You can use disableNativeSpellChecker to make it take effect:
= false;
After reloading the editor, you should see the spelling underline below the content.
Note: If the context menu plugin takes effect, you need to press the CTRL key when right-clicking to view the suggestions. Note: In general, spell checking is not available to all browsers.
SpellCheckAsYouType Plugin
The SpellCheckAsYouType (SCAYT) plugin provides inline spellchecking, which is more like a local spellchecking that integrates well with the CKEditor context menu.
It is provided by. It uses its web service, passing text to its server to perform spell checking. This is a cross-browser solution.
WebSpellChecker Plugin
The WebSpellChecker plugin is another spell checking scheme provided by , which runs checking through a dialog window instead of inline marking incorrectly spelled words.
7. File browser and upload
Integrate with file browser
CKEditor can be easily integrated with external file browsers/uploaders.
Once correctly configured, all file browser functions will automatically become available
Basic configuration
-
filebrowserBrowseUrl sets the location containing an external browser. When the Browse Server button is pressed, the browser will be started.
-
filebrowserUploadUrl sets the location that contains the processing file upload script. If set, the Upload tab will appear in some dialogue windows - if the function is available in these windows, that is, Link, Image and Flash Properties.
Example 1
The following example shows the basic configuration code that can be used to insert into a CKEditor instance configured with file browsing.
( 'editor1', { filebrowserBrowseUrl: '/browser/', filebrowserUploadUrl: '/uploader/' });
Example 2
You can also set a separate URL for the selected dialog window by using the dialog window name in the file browser settings: filebrowserBrowseUrl and filebrowserUploadUrl.
For examples of setting a special upload URL for the image dialog window, use the filebrowserImageUploadUrl property.
( 'editor1', { filebrowserBrowseUrl: '/browser/', filebrowserImageBrowseUrl: '/browser/?type=Images', filebrowserUploadUrl: '/uploader/', filebrowserImageUploadUrl: '/uploader/?type=Images' });
In the above example, the filebrowserBrowseUrl and filebrowserUploadUrl settings will be used by default. In the Image Properties dialog window, CKEditor will use the configuration settings of filebrowserImageBrowseUrl and filebrowserImageUploadUrl.
File browser window size
In CKEditor, the default width of the file browser is set to 80% of the screen width, while the default height is set to 70% of the screen height.
If the default value is not suitable for you for any reason, you can adjust it as needed, use filebrowserWindowWidth to change the width of the window, and use filebrowserWindowHeight to change the height of the window.
To define the size of the file browser window into pixels, set it to a number (such as "800"). If you like to set the height and width of the window to the percentage of the screen, don't forget to add a percent sign after the number (such as "60%").
Example 3
The basic configuration code given in the example below can be used to insert into a CKEditor that has the file browser path and window size configured.
( 'editor1', { filebrowserBrowseUrl: '/browser/', filebrowserUploadUrl: '/uploader/', filebrowserWindowWidth: '640', filebrowserWindowHeight: '480' });
To set the window size of the file browser for the specified dialog window, use filebrowserWindowWidth and filebrowserWindowHeight settings.
For example, just want to change the window size of the file browser in the "Image" dialog box and change the settings of filebrowserImageWindowWidth and filebrowserImageWindowHeight.
Example 4
The basic configuration code given in the following example can be used to insert into a CKEditor with the file browser path configured. It also changes the default size of the file browser window, but only when it opens from the Image Properties dialog window.
( 'editor1', { filebrowserBrowseUrl: '/browser/', filebrowserUploadUrl: '/uploader/', filebrowserImageWindowWidth: '640', filebrowserImageWindowHeight: '480' });
Using CKFinder
CKEditor can be easily integrated with CKFinder, which is an advanced Ajax file browser. Check out the live demonstration here.
Integration can be achieved in two ways: by setting the CKEditor configuration options (the example below) or by using the () method available in the CKFinder API.
Example 5
The configuration code given in the example below can be used to insert into a CKEditor integrated with CKFinder. The browsing and upload paths for images and Flash objects are configured separately from the default paths of CKFinder.
( 'editor1', { filebrowserBrowseUrl: '/ckfinder/', filebrowserImageBrowseUrl: '/ckfinder/?Type=Images', filebrowserFlashBrowseUrl: '/ckfinder/?Type=Flash', filebrowserUploadUrl:'/ckfinder/core/connector/php/?command=QuickUpload&type=Files', filebrowserImageUploadUrl:'/ckfinder/core/connector/php/?command=QuickUpload&type=Images', filebrowserFlashUploadUrl:'/ckfinder/core/connector/php/?command=QuickUpload&type=Flash' });
The above example is valid for PHP environment. Note: /ckfinder/ is the base path of the CKFinder installation target.
If you want to use CKFinder in ASP, , , or ColdFusion, remember to modify the above php to the correct extension:
-
asp – CKFinder for ASP
-
aspx – CKFinder for
-
cfm – CKFinder for ColdFusion
-
php – CKFinder for PHP
Example 6
The following example illustrates the use of () which can be inserted into a CKEditor instance integrated with CKFinder.
var editor = ( 'editor1' ); ( editor, '/ckfinder/' );
The second parameter of the SetupCKEditor() method is the installation path of CKFinder.
Please check out the _samples/js/ example published with CKFinder for a complete working example of this integration method.
CKEditor4 PHP API
As for CKFinder 1.4.2 and CKEditor 3.1, you can use the PHP API to integrate CKFinder with CKEditor. For more details, see the CKFinder for PHP documentation. Other resources
For more advanced information on integrating CKEditor with file browser, see the following article:
-
Creating a Custom File Browser (generate a customized file browser)
-
Adding the File Browser to Dialog Windows (Add file browser to the dialogue window)
CKEditor4 File Browser API
CKEditor can be easily integrated with your own file browser.
To connect to a file browser compatible with CKEditor (such as CKFinder), follow the File Browser (Uploader) document.
Interaction between CKEditor and file browser
CKEditor automatically sends some additional parameters to the file browser:
-
CKEditor – CKEditor instance name,
-
langCode – CKEditor's language (English is en),
-
CKEditorFuncNum – Anonymous function reference number, used to pass the URL of the file to CKEditor (a random number).
For example:
CKEditor=editor1&CKEditorFuncNum=1&langCode=en
Example 1
Suppose CKEditor is generated by the following JavaScript call:
( 'editor2', { filebrowserBrowseUrl: '/browser/?type=Images', filebrowserUploadUrl: '/uploader/?type=Files' });
To browse the file, CKEditor will call:
/browser/?type=Images&CKEditor=editor2&CKEditorFuncNum=2&langCode=de
The call includes the following elements:
-
/browser/?type=Images – The value of filebrowserBrowseUrl parameter
-
&CKEditor=editor2&CKEditorFuncNum=2&langCode=de – Information added by CKEditor:.
CKEditor=editor2 – CKEditor instance name (editor2),
CKEditorFuncNum=2 – The reference number of the anonymous function will be used in callFunction, o langCode=de – Language encoding (in this example: German). This parameter can be used to send localized error messages.
Pass the URL of the selected file
To return the URL of the file from an external file browser, call, and pass CKEditorFuncNum as the first parameter:
( funcNum, fileUrl [, data] );
If data (third parameter) is a string, it will be displayed by CKEditor. If a problem occurs while uploading a file, this parameter is usually displayed as an error message.
Example 2
The following example shows how to pass a URL from a file browser using JavaScript code:
// Helper function to obtain parameters from query string
function getUrlParam( paramName ) { var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' ) var match = (reParam) return ( match && > 1 ) ? match[ 1 ] : null } var funcNum = getUrlParam( 'CKEditorFuncNum' ); var fileUrl = '/path/to/'; ( funcNum, fileUrl );
Example 3
The following code shows how to transfer back the URL of the uploaded file from the PHP connector:
<?php // Required: anonymous function reference number as explained above. $funcNum = $_GET['CKEditorFuncNum'] // Optional: instance name (might be used to load a specific configuration file or anything else). $CKEditor = $_GET['CKEditor'] // Optional: might be used to provide localized messages. $langCode = $_GET['langCode'] // Check the $_FILES array and save the file. Assign the correct path to a variable ($url). $url = '/path/to/uploaded/'; // Usually you will only assign something here if the file could not be uploaded. $message = echo "<script type='text/javascript'>($funcNum, '$url', '$message');</script>"; ?>
Example 4
If data is a function, it will be executed within the scope of the button that calls this file browser. This means that the server connector can directly access the conversation window to which the CKEditor and the button belong.
Suppose that in addition to passing the fileUrl that is automatically assigned to the corresponding domain according to the dialog window definition, if the file browser is open in the Image Properties dialog window, you also want to set the alt property. To do this, pass the anonymous function as the third parameter:
( funcNum, fileUrl, function() { // Get a reference to the dialog window var element, dialog = (); //Check whether it is an Image dialog window if ( () == 'image' ) { // Get a reference to a text field with "alt" attribute element = ( 'info', 'txtAlt' ); // Assign new values if ( element ) ( 'alt text' ); } ... // Return false, stop further execution - - In this case, CKEditor will ignore the second parameter (fileUrl) // and the onSelect function assigned to the call file browser button (if defined). [return false;] });
Add file browser to dialog box
CKEditor can be easily integrated with your own file browser.
To connect to a file browser compatible with CKEditor (such as CKFinder), follow the File Browser (Uploader) document.
Dialog Box
Please refer to the Dialog definition API for general help on how to generate a dialog box.
Filebrowser plugin
The filebrowser plugin is built into CKEditor. Its sole purpose is to provide an API in CKEditor that integrates any external file browser and adds file browsing capabilities to various CKEditor components (usually dialog boxes).
Add "Browse Server" button
To add a file browser plugin to an element in a dialog box, set the "filebrowser" property. In the example of image plugin, there are:
{ type: 'button', hidden: true, id: 'browse', filebrowser: ' Link:txtUrl', label: , style: 'float:right', },
This button is hidden by default (hidden:true).
The file browser plugin looks for all elements with the filebrowser attribute and no longer hides them if there are corresponding configuration settings available (filebrowserBrowseUrl/filebrowserUploadUrl).
The operations performed by the plugin depend on the type of the element. For fileButton, the operation is QuickUpload, and for other elements, the default operation is Browse. In the example above, when the button is clicked, the file browser will be started (in the pop-up window).
The value of 'Link:txtUrl' tells the plugin to update the element in the Link tag with id txtUrl when calling ( funcNum ).
Add "Quick Upload" support
Again, look at how to handle file uploads in our dialog, we will use a working example from CKEditor. In the image plugin, there is an Upload tag definition:
{ id: 'Upload', hidden: true, filebrowser: 'uploadButton', label: , elements: [ { type: 'file', id: 'upload', label: , style: 'height:40px', size: 38 }, { type: 'fileButton', id: 'uploadButton', filebrowser: 'info:txtUrl', label: , 'for': [ 'Upload', 'upload' ] } ] },
This example is a little more complicated than the previous example because
1) Here is the definition of the entire tag
2) We need two elements: file and fileButton to upload the file.
In the example above, the id of the tag is 'Upload'. It is hidden by default (hidden:true).
As mentioned, the file browser plugin looks for all elements with the filebrowser attribute and does not hide them if the corresponding configuration settings are available.
In this example, if the 'uploadButton' file browser setting (because filebrowser:'uploadButton') becomes available (filebrowserUploadUrl), this tag will automatically no longer be hidden.
The file element is simple and does not need to be explained. It is just an input element that will save the file name to be uploaded.
The fileButton element is more interesting. The 'info:txtUrl' value enables the file browser plugin to update the element with id txtUrl in the info tag when calling ( funcNum ) (see Custom File Browser). 'for': [ 'Upload', 'upload' ] A line is used to associate a fileButton with a file element. It is an instruction to upload a file by CKEditor, using the 'file' element with id 'upload' in the 'Upload tag' (first value).
Advanced configuration (browse)
You can define your own function and you can call it when selecting/uploading a file.
{ type: 'button', hidden: true, id: 'id0', label: , filebrowser: { action: 'Browse', // target: 'tab1:id1', onSelect: function( fileUrl, data ) { alert( 'The selected file URL is "' + fileUrl + '"' ); for ( var _info in data ) alert( 'data[ "' + _info + '" ]' + ' = ' + data[ _info ] ); var dialog = (); ( 'tab1', 'id1' ).setValue( data[ 'fileUrl' ] ); //Do not call the built-in onSelect command return false; } } }
In this example, we set up the 'Browse' operation, which calls the file browser when the button is clicked. 'target' is not required, as we will update the target element in the customized onSelect function.
As explained in this document, when the user selects a file, we have called ( funcNum, fileUrl, data);. The fileUrl and data parameters are passed to our customized onSelect function, which we can use to update the target element.
Advanced configuration (quick upload)
Use our configuration button to open the file browser the same method, we configure fileButton.
{ type: 'file', label: , labelLayout: 'vertical', id: 'id2' }, { type: 'fileButton', label: , id: 'id3', filebrowser: { action: 'QuickUpload', params: { type: 'Files', currentFolder: '/folder/' }, target: 'tab1:id1', onSelect: function( fileUrl, errorMessage ) { alert( 'The url of uploaded file is: ' + fileUrl + '\nerrorMessage: ' + errorMessage ); // Do not call the built-in onSelect command // return false; } }, 'for': [ 'tab1', 'id2' ] }
In the properties, we can add other parameters to pass them to the external file browser in the query string. It is the target element that is updated when the file is returned through the server connector (uploader) - if we define our own onSelect function() and update the target element in this function, just like in the previous example, we do not need this target element.
4. CKEditor4 customization
1. CKEditor4 plug-in
CKEditor is completely plugin-based. In fact, the heart of the editor is an empty box that is populated by features provided by the plugin. Even the editor's interfaces, such as toolbars, buttons and editing areas, are plug-ins.
The default installation of CKEditor, which you may be using, has some plugins that appear in it. You can add plugins to your editor to bring better and more useful features to your users.
Where to find plugins?
CKEditor Add-ons Repository is an online service for finding and sharing plug-ins. It can easily understand the plug-in functions and interact with the CKEditor group. If you are a plugin developer, it is also the best place to showcase your skills and gain a large user base.
Use CKBuilder to generate a customized editor
CKBuilder is a sister service of CKEditor Add-ons Repository. You can generate customized editors by choosing plugins that are more suitable for your needs.
Through the plug-in navigation, you can use "Add to my editor button" to send your favorite plug-ins to your customized editor. Once done, you can simply download the plugin and enjoy the editing experience you need perfectly.
Manually install plug-ins
If you don't like using CKBuilder, if you have your own or third-party plugins, or if you just want to test the plugin before going through the CKBuilder process, you can also add the plugin to your local installation through the following steps:
1. Unzip the zip file: The plug-in is usually a zip file. So to start, make sure to unzip the zip file into a folder.
2. Copy files into CKEditor: The easiest way to install files is by simply copying the files into the plugins folder of the CKEditor installation directory. Must be placed in a subfolder that matches the plugin's "technology" name. For example, MagicLine plugin will be installed in a folder like this: <CKEditor folder>/plugins/magicline.
3. Make the plugin effective: Now is the time to tell CKEditor that you have added a new plugin for it. To do this, you simply use extraPlugins configuration options: = 'magicline'; That's all. Now your plug-in can be effective in CKEditor.
2. Skin
The user interface appearance of CKEditor can be customized through skins. Elements like toolbars, dialog boxes, buttons, and even their icons can be changed in the style you like.
The default installation of CKEditor has Moono skin.
Where to find skin?
CKEditor Add-ons Repository is an online service for finding and sharing skins. If you are a skin developer, it is also the best place to showcase your skills and gain a large user base.
Download CKEditor with your favorite skins
CKBuilder is a sister service of CKEditor Add-ons Repository, which can generate customized editors with required skins.
Manually install skin
If you don't like using CKBuilder, if you have your own or third-party skins, or if you just want to test your skin before going through the CKBuilder process, you can also add the skin to your local installation through the following steps:
1. Unzip the zip file: The skin is usually a zip file. So to start, make sure to unzip the zip file into one
in folder.
2. Copy files into CKEditor: The easiest way to install files is by simply copying the files to
CKEditor installation directory in skins folder. Must be placed in a subfolder that matches the skin's "technology" name. For example, Kama skin will be installed in a folder like this: <CKEditor folder>/skins/kama.
3. Enabling the plugin: Now you must just setup CKEditor, by using the skin configuration
option:
4. Make the plugin effective: Now you only need to configure CKEditor, by using skin configuration options: = 'kama';
That's it. Now the new skin can be effective in CKEditor.
The CKEditor4 description document is very large. Here I only share some commonly used configuration and development Chinese description documents for CKEditor4. If you need more details, you can check it on the official website of CKEditor4.