Skip to Content
Post Canvas
Guides

Migrating from TinyMCE or Froala

Move existing HTML content into Post Canvas with fromHTML, check what was lost, and see which TinyMCE and Froala features have an equivalent.

TinyMCE and Froala store a post as an HTML string. Post Canvas stores a post as JSON (see Document JSON). To move over, you convert each HTML string once with fromHTML(), check the result, and save the JSON. The HTML is read through Post Canvas's schema, so anything the schema has no place for is left out, and then the result is sanitized.

Keep the old HTML column until you have checked a sample of posts in the new editor.

Convert HTML to a document

In a browser, fromHTML() uses the browser's own DOMParser:

import { fromHTML } from 'post-canvas/render';

const doc = fromHTML(legacyHtml);

On a server there is no DOMParser, so pass { window } from a DOM library such as happy-dom or linkedom. Both are shown in Server rendering. The window needs no cast.

import { fromHTML } from 'post-canvas/server';
import { Window } from 'happy-dom';

const doc = fromHTML(legacyHtml, { window: new Window() });

Scripts in the HTML never run: it is parsed into an inert document first. HTML over 1,000,000 characters, or nested deeper than 512 elements, throws a RangeError, so on a server wrap the call in try/catch (the script below does).

To open an old post for editing, convert it first and pass the JSON as defaultContent. That way the document went through the sanitizer before it reached the editor.

What is kept and what is dropped

KeptNotes
Paragraphs, headings 1 to 4h5 and h6 become heading 4, keeping their text
Text alignmentFrom style="text-align: ...": left, center, right, justify
Bold, italic, underline, strikethrough, inline code, subscript, superscriptFrom the tags, and bold and italic also from font-weight and font-style styles
Linkshttp, https, mailto, tel and relative addresses. target="_blank" is kept and rel is set to a safe value
Bulleted, numbered and nested listsA numbered list keeps its start number
TablesHeader cells, colspan and rowspan
Quotes, dividers, line breaks
Code blocksA language-... class on pre or code sets the language
ImagesWith an http or https address. Width and height attributes are kept. A figure with a figcaption becomes an image with a caption
YouTube and Vimeo iframesBecome video blocks. A start time is kept
Other player iframesSpotify, SoundCloud, X, Instagram, TikTok, CodePen, Loom, Figma and Google Maps become embed blocks, if the embed feature allows that provider
CKEditor oembed elementsTreated like an iframe with the same address
Task listsOnly from Tiptap's own markup (data-type="taskList")
DroppedWhat happens
script, style, template, noscript, object, embed, link, meta elementsRemoved with their content
Classes, ids and inline stylesRemoved. The few styles above are read before that
Text color, background color, font family, font size, line height, indentationRemoved. Colors in Post Canvas are nine named palette colors, so there is no exact mapping
mark and highlighted textBecomes a highlight in the default color, whatever its original color
Unknown tags and wrappers such as div, section, font, custom elementsUnwrapped: the text and any known children stay
Images with a relative address or a data: addressDropped, leaving an empty paragraph
Iframes from other sites, video and audio elements, formsDropped
Table widths, borders, cell colors, colgroupDropped
Checkbox lists written as plain input elementsBecome plain bulleted lists
Mentions from another editor's markupBecome plain text
Anchors with a name but no hrefUnwrapped to text

Two of these catch most migrations out: relative image paths (TinyMCE writes them by default) and base64 images. Resolve relative paths to full addresses before you convert, and upload base64 images to your storage first. The script below does the first.

A batch script

This script reads legacy-posts.json (an array of { id, html }), converts every post with happy-dom, checks each result, and writes migrated-posts.json and a report. Adapt the input and output to your database.

scripts/migrate-posts.ts
import { readFile, writeFile } from 'node:fs/promises';
import { Window } from 'happy-dom';
import { fromHTML, resolveFeatures, sanitizeDocument, toPlainText } from 'post-canvas/render';
import type { JSONContent } from 'post-canvas';

const SITE = 'https://www.example.com'; // where relative image paths point
const features = resolveFeatures('article'); // the features your editor will use

const window = new Window();

/** Makes relative image addresses absolute, because fromHTML drops anything that is not http or https. */
function absolutizeImages(html: string): string {
  const parsed = new window.DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
  for (const img of Array.from(parsed.querySelectorAll('img'))) {
    const src = img.getAttribute('src') ?? '';
    if (src && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) img.setAttribute('src', new URL(src, SITE).href);
  }
  return parsed.body.innerHTML;
}

function words(text: string): number {
  return text.split(/\s+/).filter(Boolean).length;
}

const posts = JSON.parse(await readFile('legacy-posts.json', 'utf8')) as { id: string; html: string }[];
const migrated: { id: string; doc: JSONContent }[] = [];
const report: { id: string; warnings: string[] }[] = [];

for (const { id, html } of posts) {
  const source = absolutizeImages(html);
  const warnings: string[] = [];

  // 1. Everything fromHTML left out: stripped scripts and styles, pictures and frames it refused, and what the
  //    sanitizer removed afterwards.
  let doc: JSONContent;
  try {
    doc = fromHTML(source, {
      window,
      features,
      onRemoved: (removed, omitted) => {
        const kinds = removed.map((item) => item.type ?? item.reason).join(', ');
        if (removed.length > 0 || omitted > 0) warnings.push(`left out ${removed.length + omitted}: ${kinds}`);
      },
    });
  } catch (error) {
    // A RangeError means the HTML is over the length limit or nested too deeply.
    report.push({ id, warnings: [`not converted: ${error instanceof Error ? error.message : String(error)}`] });
    continue;
  }

  // 2. A second check against the features of your real editor, such as a table in a `comment` preset.
  const { removed, omitted } = sanitizeDocument(doc, { features });
  if (removed.length > 0 || omitted > 0) warnings.push(`sanitizer removed ${removed.length + omitted}`);

  // 3. A big drop in words means something went wrong. Formatting such as colours is dropped without a record.
  const before = words(source.replace(/<(script|style)[\s\S]*?<\/\1>/gi, '').replace(/<[^>]+>/g, ' '));
  const after = words(toPlainText(doc));
  if (before > 0 && after < before * 0.9) warnings.push(`text shrank from ${before} to ${after} words`);

  migrated.push({ id, doc });
  report.push({ id, warnings });
}

await writeFile('migrated-posts.json', JSON.stringify(migrated));
await writeFile('migration-report.json', JSON.stringify(report.filter((r) => r.warnings.length > 0), null, 2));
console.log(`${migrated.length} posts converted, ${report.filter((r) => r.warnings.length > 0).length} with warnings`);

Run it with a TypeScript runner such as npx tsx scripts/migrate-posts.ts. The script uses top-level await, so the project needs "type": "module" in its package.json.

About removed

onRemoved(removed, omitted) receives what fromHTML() left out while it read the HTML: elements it stripped before parsing (script, style, template, noscript, object and embed), pictures and frames the schema refused (a relative or data: image, a player from a site it does not know), and whatever sanitizeDocument() removed afterwards, such as a node type your features turn off. Each item has a path, a reason and a type. At most 100 items are listed, and omitted counts the rest.

Formatting the schema has no place for is dropped without a record: colours, fonts, sizes and table styling. That is why the script also compares word counts with the source. Running sanitizeDocument() again with the features of your real editor, as the script does, shows what your preset would remove, for example a table in a comment preset.

Paste from Word and Google Docs

Writers paste into the editor too, and pasting is cleaned the same way for every source. cleanPastedHTML() runs on every paste:

  • Keeps headings, paragraphs, lists, tables, links, quotes, code and inline formatting. Removes styles, classes, ids, event handlers, scripts, comments and Office markup.
  • Rebuilds real lists from Word's list paragraphs (mso-list), including nesting and the bullet or number kind.
  • Turns Word's Title and Subtitle styles into headings, and h5 and h6 into heading 4.
  • Unwraps the wrapper that Google Docs puts around a copied selection.
  • Turns bold, italic, underline, strikethrough, superscript and subscript written as inline styles into real formatting.
  • Splits pasted plain text into paragraphs at blank lines, and turns single line breaks into line breaks.
  • With an upload adapter, pictures pasted as data: addresses are uploaded through it. Without one they are dropped. Pictures with an http or https address stay as links to that address.

fromHTML() does not rebuild Word lists. If you have Word HTML as a file, open it in a browser, copy it, and paste it into the editor, or run cleanPastedHTML(html) in a browser before fromHTML(). cleanPastedHTML needs a browser DOMParser.

Option mapping

TinyMCE or FroalaIn Post Canvas
toolbar, plugins (TinyMCE), toolbarButtons (Froala)preset and features. There is no toolbar builder: you turn features on or off, and the toolbar's order and groups are fixed
height, min_height, heightMinCSS on .pc-content, and a className on PostCanvas. See Theming
skin, content_css, dark modeThe theme prop and --pc-* tokens
images_upload_handler, imageUploadURLadapters.upload. See Uploads
file_picker_callback, media libraryNo built-in file browser. Build your own and call editor.commands.insertImage()
table pluginfeatures.table
lists, advlistbulletList, orderedList, taskList
codesamplefeatures.codeBlock, with a language menu and syntax highlighting
link, autolinkfeatures.link. Typed addresses become links as you type
mentionsadapters.mentions and adapters.hashtags. See Mentions and hashtags
media, quickInsertThe + button, the / menu, and pasting a video or embed address
wordcount, charCounterMaxThe status bar, and limits (maxWords, maxCharacters, maxMedia, maxPhotos)
autosaveThe autosave prop. See Autosave
getContent(), html.get()onChange for JSON, renderToHTML(json) for HTML
setContent(), html.set()The ref's setContent(content, format)
valid_elements, htmlAllowedTagsNo allow-list setting. The schema decides. Add your own node types with extensions (Headless usage)
forecolor, backcolor, font family and sizeNine named colors for text and highlight. No free color, font or size
Source code viewNone
Spell check, Froala's spell checkerThe browser's own spell check. No spell-check interface
Comments, collaboration, revisions, track changesNone. See the roadmap
Templates, merge tags, export to PDF or WordNone. You can get Markdown and plain text with toMarkdown() and toPlainText()
Emoji pickerNone. The system emoji picker works, and shortcodes are on the roadmap

Content that depends on the lines marked None needs a separate decision before you move. In particular, if writers rely on exact colors, fonts or table styling, that formatting does not survive.

On this page