TinyMCE is a great editor to build on, but its image handling assumes you want TinyMCE's way of doing things: an image dialog with a URL field, an optional upload tab, and pasted images that end up as base64 unless you set up an upload handler. If your app already has an asset library, with uploads, search, alt text and a CDN, you want the editor to use that instead.
We did exactly that in the PresenceWave dashboard, where TinyMCE powers blog posts, job posts and emails. This post walks through how, with the code. It targets TinyMCE 6 (self-hosted, open source) and uses Vue 3 for the dialog, but the plugin itself works with any framework.
The complete plugin, a demo you can run in a minute and a Vue example are on GitHub: JulioLabs/tinymce-asset-library-plugin.
What we wanted
- A toolbar button and an Insert menu item, "Insert image from assets", that open our own asset picker and insert the chosen image with its saved alt text.
- The browse button in TinyMCE's image dialog opens the same picker.
- Pasted and dropped images are uploaded to the asset library and replaced by their CDN URL. No base64 in the content.
- One plugin file that knows nothing about Vue or our API, so every editor in the app gets it for free.
The hooks TinyMCE gives you
TinyMCE 6 has everything needed, spread across a few options:
| Hook | What it does |
|---|---|
images_upload_handler | Called for every pasted or dropped image (and the image dialog's Upload tab). Must return a promise of the image URL as a string. |
file_picker_callback | Adds a browse button next to the URL field in the image, link and media dialogs. You call callback(url, meta) when the user has picked something. |
editor.ui.registry.addButton / addMenuItem | Your own toolbar button and menu item. |
editor.options.register | Lets a plugin declare its own options, so the host app can pass functions in. |
PluginManager.add | Registers a plugin from your own bundle. |
Two bugs worth knowing about
Before writing the plugin, we found out why pasting an image into our editor had never worked. Both causes are easy to make:
- The upload handler must resolve with a string. Ours resolved with
{ url, alt }. TinyMCE uses whatever you resolve with as the image'ssrc, so the image would have becomesrc="[object Object]". There's no way to pass alt text through this handler. - The form field name must match the server. The handler sent
formData.append("file", …)while the endpoint expectedfiles, so every upload was refused with a 400 before it got that far.
Step 1: register the plugin from your own bundle
A plugin is a function that receives the editor. Register it once, when your editor module loads:
import "tinymce/tinymce";
export const PLUGIN_NAME = "pwassets";
window.tinymce.PluginManager.add(PLUGIN_NAME, (editor) => {
registerOptions(editor);
registerUi(editor);
registerFilePicker(editor);
registerUploads(editor);
return {
getMetadata: () => ({ name: "PresenceWave assets" }),
};
});
Gotcha: registering the plugin isn't enough. PluginManager.add doesn't mark it as loaded, so if you list pwassets in plugins, TinyMCE still tries to fetch plugins/pwassets/plugin.min.js from its base URL and shows a "Failed to load plugin" notification. Prefix the name with a dash and TinyMCE skips the download:
export const PLUGIN_ENTRY = `-${PLUGIN_NAME}`; // "-pwassets"
plugins: ["link", "image", "lists", /* … */ PLUGIN_ENTRY].join(" "),
TinyMCE strips the dash before it initialises the plugin, so buttons and menu items are still called pwassets.
Step 2: let the host app pass the picker and the upload in
The plugin shouldn't import your API client or your UI framework. Instead it declares two options, and the app passes functions in through the editor config:
const registerOptions = (editor) => {
// pick({ filetype }) -> Promise<{ url, altText } | null>
editor.options.register("pwassets_pick", { processor: "function" });
// upload(blob, fileName) -> Promise<{ url, altText }>
editor.options.register("pwassets_upload", { processor: "function" });
};
const pickAsset = (editor, filetype) => {
const pick = editor.options.get("pwassets_pick");
return pick ? Promise.resolve(pick({ filetype })) : Promise.resolve(null);
};
The picker resolves with null when the user closes it without choosing, so every caller just checks for an asset.
Step 3: the toolbar button and menu item
Both run one editor command, which opens the picker and inserts the image. Build the HTML with editor.dom.createHTML, which escapes the attribute values, rather than gluing strings together:
const INSERT_COMMAND = "pwInsertAsset";
const registerUi = (editor) => {
editor.addCommand(INSERT_COMMAND, () => {
pickAsset(editor, "image").then((asset) => {
if (asset) {
editor.insertContent(editor.dom.createHTML("img", { src: asset.url, alt: asset.altText || "" }));
}
});
});
editor.ui.registry.addButton(PLUGIN_NAME, {
icon: "image",
tooltip: "Insert image from assets",
onAction: () => editor.execCommand(INSERT_COMMAND),
});
editor.ui.registry.addMenuItem(PLUGIN_NAME, {
icon: "image",
text: "Image from assets...",
onAction: () => editor.execCommand(INSERT_COMMAND),
});
};
Then put pwassets in the toolbar, and in the Insert menu by listing that menu's items:
toolbar: "undo redo | bold italic | bullist numlist | pwassets link media",
menu: { insert: { title: "Insert", items: "pwassets image link media inserttable | charmap hr" } },
We kept TinyMCE's own image plugin. It's still the best way to edit an inserted image's alt text and size from the context menu.
Step 4: the image dialog's browse button
file_picker_callback gives the image dialog a browse button. When the user picks an asset, the callback fills in the URL, and for images the alt in the meta object fills in the alt text field too:
// Sets a core option unless the app's own config already did
const setDefault = (editor, name, value) => {
if (!editor.options.isSet(name)) {
editor.options.set(name, value);
}
};
const registerFilePicker = (editor) => {
setDefault(editor, "file_picker_types", "image");
setDefault(editor, "file_picker_callback", (callback, value, meta) => {
pickAsset(editor, meta.filetype).then((asset) => {
if (asset) {
callback(asset.url, { alt: asset.altText || "" });
}
});
});
};
Setting core options from inside the plugin keeps everything about images in one file. setDefault still lets an app override any of them. Turn off the dialog's own Upload tab in the config, so uploads only happen in your picker:
image_uploadtab: false,
Step 5: pasted and dropped images
With paste_data_images: true and automatic_uploads: true, TinyMCE inserts a pasted image as a local blob, calls images_upload_handler, and swaps in the URL you resolve with. Two details matter. Resolve with the URL string, and when the upload fails, reject with remove: true so TinyMCE takes the broken image out of the content instead of leaving a blob behind:
const registerUploads = (editor) => {
setDefault(editor, "images_upload_handler", (blobInfo) => {
const upload = editor.options.get("pwassets_upload");
if (!upload) {
return Promise.reject({ message: "Image upload isn't available here", remove: true });
}
return upload(blobInfo.blob(), blobInfo.filename())
.then((asset) => asset.url)
.catch((error) => Promise.reject({ message: `Image upload failed: ${error.message}`, remove: true }));
});
};
TinyMCE shows the rejection's message as its own notification, so it's worth passing on the server's reason, for example "Can't tell what type of file 'scan.heic' is", rather than a generic "Request failed with status code 415".
Step 6: wire it up in Vue
The editor component supplies the two functions. The picker is a normal Vue dialog, and the trick is to turn "open the dialog, wait for a choice" into a promise:
<template>
<Editor :init="editorConfig" v-model="content" />
<AssetPickerDialog
v-model="assetPickerOpen"
@select="resolveAssetPick"
@cancel="resolveAssetPick(null)"
/>
</template>
<script>
export default {
data() {
return { assetPickerOpen: false, pendingAssetPick: null };
},
computed: {
editorConfig() {
return createEditorConfig({
pickAsset: this.pickAsset,
uploadAsset: this.uploadAsset,
// height, placeholder, …
});
},
},
methods: {
pickAsset() {
this.resolveAssetPick(null); // a picker still open counts as cancelled
return new Promise((resolve) => {
this.pendingAssetPick = resolve;
this.assetPickerOpen = true;
});
},
resolveAssetPick(asset) {
const resolve = this.pendingAssetPick;
this.pendingAssetPick = null;
if (resolve) resolve(asset);
},
async uploadAsset(blob, fileName) {
const formData = new FormData();
formData.append("files", blob, fileName); // the field name your endpoint expects
const { data } = await api.uploadAssets(formData);
return data[0];
},
},
};
</script>
The config factory passes them through as the plugin's options:
export function createEditorConfig({ pickAsset, uploadAsset, ...rest }) {
return {
plugins: PLUGINS.join(" "),
toolbar: TOOLBAR,
paste_data_images: true,
automatic_uploads: true,
image_uploadtab: false,
pwassets_pick: pickAsset,
pwassets_upload: uploadAsset,
// …
};
}
Every editor in the app now uses the asset library just by being a RichTextEditor.
Things we checked
-
A dialog on top of a dialog. The browse button opens our Vue (Vuetify) dialog over TinyMCE's image dialog. Vuetify's overlay sits above TinyMCE's, and typing into the picker's search box works: TinyMCE's dialog doesn't take the keyboard back. Test this with your own UI library.
-
Testing a paste without a clipboard. In an end-to-end test (we use Playwright) you can simulate a pasted image by inserting a
data:URI and asking TinyMCE to upload it:editor.setContent('<p><img src="data:image/png;base64,iVBORw0KGgo…"></p>'); await editor.uploadImages(); // the img src is now the uploaded asset's URL
How we organised it
components/editor/
RichTextEditor.vue Vue state; supplies the picker and the upload
AssetPickerDialog.vue search, image grid, upload
tinymce/
assetsPlugin.js the plugin: button, menu item, browse button, uploads
editorConfig.js TinyMCE settings
Keeping TinyMCE's settings and the plugin out of the Vue component made each piece small enough to read in one go. Adding links to files (say, a PDF from the assets) or video next is just another filetype for the same picker: set file_picker_types: "image file media" and let the picker filter by type.
The full code, with a plain JavaScript demo and the Vue example, is at github.com/JulioLabs/tinymce-asset-library-plugin under the MIT licence.