By default, the hyperlink is open in the same tab, which prevents too many tabs open in the browser leading to overtaxed computer memory, a reduction in battery life, and, for sure, a cluttered browser workspace. However, I believe that all external links should be open in a new tab, so the users won't leave your site accidentally.
To do this in CKEditor 5 by using the Link plugin, we would need to make some configuration change.
If you use CKEditor in an HTML code/template, you can update your create function like this:
ClassicEditor
.create( document.querySelector( '#editor' ), {
// ...
link: {
decorators: {
addTargetToExternalLinks: {
mode: 'automatic',
callback: url => /^(https?:)?\/\//.test( url ),
attributes: {
target: '_blank',
rel: 'noopener noreferrer'
}
}
}
}
} )
.then( ... )
.catch( ... );
If you use CKEditor with React, then update your component like this:
import React, { Component } from "react";
import PropTypes from "prop-types";
import CKEditor from "@ckeditor/ckeditor5-react";
import ClassicEditor from "ckeditor5-build-classic-dna";
class CKEditor5 extends Component {
static get propTypes() {
return {
value: PropTypes.string,
onChange: PropTypes.func,
};
}
render() {
return (
<CKEditor
editor={ClassicEditor}
data={this.props.value}
config={{
link: {
decorators: {
addTargetToExternalLinks: {
mode: "automatic",
callback: (url) => /^(https?:)?\/\//.test(url),
attributes: {
target: "_blank",
rel: "noopener noreferrer",
},
},
},
},
}}
onChange={(event, editor) => {
const data = editor.getData();
this.props.onChange(data);
//console.log({ event, editor, data });
}}
/>
);
}
}
export default CKEditor5;
After this, link decorators are adding target="_blank" and rel="noopener noreferrer" attributes to all external links in the document, keep the internal links open in the same tab.
In the React Component example, we use ClassicEditor from "ckeditor5-build-classic-dna", which includes code block & insert image url plugins, you can install it from: https://www.npmjs.com/package/ckeditor5-build-classic-dna
Happy Editing :-)