v2.7.4.0
← Home 한국어 GitHub

Dee Editor Manual

Dee Editor is a WYSIWYG web editor written in pure JavaScript with no external dependencies. This document covers the whole API, from installation through advanced integration.

📑 This document is the official API reference. It is the single source of truth for every option, method, event, and type. For runnable examples and integration patterns, see the 📘 Tutorial.
This document is written for the latest version, v2.7.4.0.

1. Quick start

1-1. Loading the files

Include the two files below in your HTML. You only need to load the extra plugins if you use document import.

You do not need to add each plugin <script>. You can load only the core and use the one-line setup (WebEditor.create('#editor', { preset: 'full' })) to turn on document import, Markdown, OCR, charts and the menu bar at once. Loading the plugins yourself also continues to work as before.
Minimal samples are available for the three setup methods: 1. Classic (load the files, write options in code) · 2. One-line setup (preset: 'full') · 3. Config file (dee-editor.config.js made with the admin settings tool, no options in page code). Guides: docs/01_Getting-started/SETUP_1~3.
<!-- Stylesheet -->
<link rel="stylesheet" href="dist/webeditor.min.css">

<!-- Core bundle -->
<script src="dist/webeditor.min.js"></script>

<!-- Only if you need MS Word import (optional) -->
<script src="dist/plugins/wordimport-native.min.js"></script>

<!-- Only if you need Hangul HWPX import (optional) -->
<script src="dist/plugins/hwpximport-native.min.js"></script>

1-2. Basic initialisation

<div id="editor"></div>

<script>
const editor = new WebEditor('#editor', {
  height: '400px'
});
</script>

One-line setup — the menu bar and every plugin (v2.6.8)

When you pass preset: 'full' to WebEditor.create, it first loads the document import (Word · Hangul HWP/HWPX · Excel · PowerPoint · PDF), Markdown, OCR and chart (v2.7.3.0) plugin files from plugins/ next to the core, then returns an editor with every built-in plugin and the menu bar turned on. You do not need to add each plugin <script> or keep the plugins list in sync.

<script src="dist/webeditor.min.js"></script>
<script>
WebEditor.create('#editor', { preset: 'full', height: '400px' })
  .then(function (editor) { editor.setHTML('<p>Ready</p>'); });
</script>
ParameterDescription
preset: 'full'The 11 built-in plugins + wordimport · hwpimport · hwpximport · xlsximport · pptimport · pdfimport · markdown · ocr · chart (v2.7.3.0) + the menu bar + the unified [Import document] button. AI writing (ai) is not included because it needs a server. OCR appears only when its engine (dext-ocr/) is present. The approval-form sample (approvalform) is not included.
preset: { exclude }Specifies the plugins to leave out, e.g. { name: 'full', exclude: ['pdfimport', 'ocr'] }. Those files are not fetched.
preset: { pluginPath }Specifies the folder of the plugin files. It defaults to plugins/ next to the core bundle, and if the core is .min.js, the plugins are fetched as .min.js too. Please set it for ESM or bundlers, where the core location is not known.
PrecedenceDefaults < preset < options you pass. If you pass plugins, menubar or toolbar, that value is used as is (with plugins, only the optional plugins in it are loaded). Without a preset, nothing changes.
new WebEditor(…, { preset: 'full' })This is for pages that already load the plugin <script> tags. The constructor cannot wait for files, so it only turns on the optional plugins that are already loaded.
create returns a Promise, so please call setHTML and similar methods inside then. Files already loaded are not fetched again (once even for several editors), and if a file fails to load, only that format is left out and the editor still opens (with a console warning). Please keep dist/plugins/ next to the core. If you load the core with a cache-busting value such as webeditor.min.js?v=…, the plugins are fetched with the same value, so old plugin files are not mixed in from the cache after an upgrade.

One-line setup examples

async/await example: This sets the content right after the editor is created.

const editor = await WebEditor.create('#editor', { preset: 'full', height: '500px' });
editor.setHTML(savedHtml);   // content from the server

Leaving some out: This example builds a screen without PDF and OCR. Plugins you leave out are not fetched.

WebEditor.create('#editor', {
  preset: { name: 'full', exclude: ['pdfimport', 'ocr'] }
});

Ribbon example: With uiTemplate: 'ribbon', the tab ribbon replaces the menu bar, and its import cards follow the loaded plugins.

WebEditor.create('#editor', { preset: 'full', uiTemplate: 'ribbon' });

Keeping your existing settings: Options you pass take precedence over the preset. Below, the plugin files are loaded in one line while the menu bar stays off and your toolbar layout is kept.

WebEditor.create('#editor', {
  preset: 'full',
  menubar: false,                    // wins over the preset menu bar
  toolbar: window.DEEDITOR_UI_CONFIG.toolbar,  // layout from the UI config page
  uploadHandler: uploadToServer
});

Several editors · ESM: Even with several editors on a page, each plugin file is fetched only once. When the core location is unknown (ESM, bundlers), pass pluginPath.

import WebEditor from '/dee/dist/webeditor.esm.js';
const preset = { name: 'full', pluginPath: '/dee/dist/plugins/' };
const [a, b] = await Promise.all([
  WebEditor.create('#editor-a', { preset }),
  WebEditor.create('#editor-b', { preset }),
]);

1-3. Reading and writing content

// Get the body HTML (use this on form submit)
const html = editor.getHTML();

// Set the body (when loading existing data)
editor.setHTML('<p>Saved content</p>');

// Get plain text only
const text = editor.getText();

2. Initialisation options

new WebEditor(selector, options)
OptionTypeDefaultDescription
heightstring | number'400px'Specifies the editor height.
widthstring | numbernullSpecifies the width of the whole editor. A number means px; a string is a CSS value such as '80%'. Leave it out to fill the host element. At run time, use setWidth() (the border is added on top). Even if it is wider than the host element, the editor stays inside the host element (v2.7.1.0 — so it is not cut off in a narrow window).
fixedHeight booleanfalseFixes the editor height and scrolls inside it. With false, height is treated as a minimum and the editor grows with its content. With true, height is treated as a fixed height, and overflowing content can be reached with the body's vertical scrollbar. You can switch at runtime with setFixedHeight(bool).
importMode 'unified' | 'individual''unified'Specifies how document import (Word · HWPX · XLSX · PPTX) appears in the toolbar. 'unified' (default) shows a single “Import document” button that branches on the file extension, and 'individual' shows one button per format (only for loaded plugins). The menu bar is controlled separately by menubarImportMode.
menubarImportMode 'individual' | 'unified' | 'both''individual'Specifies how import appears in the menu bar's File menu. 'individual' (default) shows one item per format (Word, Hangul HWP, Hangul HWPX, Excel, PowerPoint, PDF; the menu has enough room, so each format is easy to find), 'unified' shows a single “Import document…”, and 'both' shows “Import document…” together with the per-format items. Formats whose bundle is not loaded do not appear. It is independent of the toolbar (importMode).
placeholderstringlanguage defaultSpecifies the placeholder text shown when the editor is empty. If omitted, the default text of the UI language is used.
languagestring'ko'Specifies the UI language. 'ko' and 'en' are built in, and 'auto' detects the language. Any other language must be registered with registerLocale(). Refer to 10-A.
defaultFontstring'Malgun Gothic'Specifies the default font (reflected in the toolbar dropdown).
defaultFontSizenumber10Specifies the default font size (pt, reflected in the toolbar dropdown).
defaultLineHeightstring | number'1.2'Specifies the default line-height multiplier (reflected in the toolbar dropdown).
undoGranularity'char' | 'group''char'Specifies the undo granularity: one character (a completed syllable for Korean) or grouped.
undoMaxBytesnumber67108864 (64MB)Specifies the memory cap for the undo history (bytes, counted as UTF-16). The oldest steps are removed first and the latest two are always kept, so long editing sessions on a large document with images do not use too much memory in the tab. 0 means no cap.
documentBackgroundobject{ mode: 'auto', inlineThreshold: 10240, store: 'auto' }Specifies how document background images are handled and preserved (small <10KB = base64, large = upload).
uiTemplate'classic' | 'ribbon''classic'Specifies the menu UI template: classic (menu bar + toolbar) or ribbon (tabs + large icons + font quick bar).
iconThemestring'default'Specifies the icon theme (default · gray · blue · colorful · vivid · natural · modern · glass · solid · emoji, or a folder name).
iconThemePathstring'assets/icon-themes'Specifies the base path for the icon theme folders.
imageEditorObject | falsenullSpecifies image editing (DEXT Image 2.2, built in). false hides the button, and an object sets { path, mode, target, actionBar, dblclick, editorOptions }. Refer to 9-G.
tableBorderColorstring'#000000'Specifies the default table cell border colour. Change it at runtime with setTableBorderColor().
tableLockObject | falsenullSpecifies table and cell locking (data-we-lock). By default, markers are honoured and the lock menu is hidden. You can change this with { menu, showIcon, allowSourceView }, and false ignores the markers. See setTableLock().
ocrObjectnullSpecifies the text recognition (ocr plugin) settings: { dextOcrUrl, output, hideWhenNoProvider, privacy, html, ocrOptions }. See 9-L.
ai v2.7.1.1ObjectnullSpecifies the AI writing (ai plugin) settings: { endpoint, provider, scope, guard, onGuard, markGenerated, titleInput, onTitle, templates, … }. See 9-N.
chart v2.7.3.0ObjectnullChart (chart plugin) settings. { output, defaultType, palette } — see 9-O-7.
toolbarOverflowbooleantrueIndicates whether the toolbar, when it exceeds its width, stays on one line and folds the overflow into a » (more) popup. Folding happens one icon at a time, so even a long run without separators (|) shows as much as fits and folds only what overflows (groups return when there is room again). With false, the toolbar wraps to the next line as before. A live demo is available in demo/ui-config.html under “narrow width / overflow preview”.
contentCSSstringnullSpecifies extra CSS applied inside the editing area.
readOnlybooleanfalseIndicates whether the editor runs in read-only mode.
autofocusbooleanfalseIndicates whether the editor receives focus right after initialisation.
enterKey'p' | 'br''p'Specifies the tag inserted by the Enter key.
maxImageWidthnumbernullSpecifies the maximum displayed width for inserted images (px, 0 = unlimited). It applies CSS max-width only, and the original file is untouched.
imageResizeobject | nullnullSpecifies resizing that re-encodes at fewer actual pixels, so the base64 in the body and the uploaded file both shrink (§2-1-8).
pastePlainTextbooleanfalseIndicates whether formatting is removed on paste.
siteConfig v2.6.8false | object—Specifies whether to read the site config file (window.DEEDITOR_CONFIG). If omitted, the file is read; false does not read it, and an object is used as the content. See 2-2-1.
sanitizeOnLoad v2.6.8booleantrueIndicates whether anything executable (on* events · script · iframe · object · javascript: URLs · dangerous CSS) is removed before HTML enters the body. Applies to setHTML · insertHTML · appendHTML · the HTML tab · the DOM API · document import at the cursor, with the same rules as getSafeHTML() (formatting · tables · images · <style> · data-* are kept). false restores the old behavior. We recommend using it only where the server has already sanitised the HTML.
autoNormalize v2.7.1.0booleantrueIndicates whether tags are cleaned up automatically while editing. Right after joining lines (Backspace · Delete), Enter, paste, drop, formatting a selection, it removes redundant tags that do not change the look (empty spans · nested spans · ineffective styles and so on) in the edited paragraph and its neighbours, and wraps top-level text in <p> (at the end of IME composition it only does this wrapping). false restores the previous behaviour. See 9-M.
normalizeOnGet v2.7.1.0booleanfalseIndicates whether getHTML() and getSafeHTML() clean up the whole body before returning (no structural fixes). Turning it on makes the same content save as different HTML than before, so we recommend it for new integrations. See 9-M.
pageGuide v2.6.8boolean | objectfalseIndicates whether to draw an A4 print-width guide line on the right of the content (186mm from the left inner padding — the text width of A4 with 12mm margins). Text that runs past the line wraps at that point when printed. It is drawn on screen only (no trace in the content HTML, saved files or print), follows zoom and horizontal scrolling, and hides in read-only mode and the HTML tab. It can also be controlled by View › Show ⟷ Hide A4 Print Width, the ribbon View tab, setPageGuide(bool), getPageGuide() ({ on, paper, margin, width, visible, warn, overflow }) and the pageGuideChange event. The line assumes the browser's print scale is 100% (default).
Overflow alerts — when the caret goes past the line it turns orange, and the status bar shows "Past A4 width — N text lines · N tables/images" (click to jump to the first one). Text re-wraps when printed; tables, images, shapes and code blocks are cut or shrunk. If the screen is narrower than A4, it reports that nothing can cross the line. Use the pageGuideOverflow event ({ count, lines, objects:[{ kind, node }] }) for checks such as a warning before submitting. To show only the line, use pageGuide: { warn: false }.
Edit at A4 width — pageGuide: { mode: 'fit' } (View › Edit at A4 Width ⟷ Full Width, ribbon) narrows the text area to 186mm so lines break on screen exactly where they break in print (the area to the right is shaded). The content HTML does not change; only the editing area's right padding changes. Wide tables and images are still reported.
showTableGuidebooleanfalseIndicates whether borderless tables are shown with dotted guides.
logoUrlstringnullSpecifies the logo image URL shown in the About dialog.
licensestringnullSpecifies the licence key (WED2-XXXX-...).
licenseLang'ko' | 'en' | nullnullSpecifies the language of the licence modal (null = automatic).
trustedHostsstring[][]Specifies trusted hosts for air-gapped networks (wildcards supported). ⚠️ This works only when a key is supplied. Without one, it stays in trial mode.
offlineModebooleanfalseIndicates whether ECDSA verification is skipped where Web Crypto is unavailable (HTTP). ⚠️ This works only when a key is supplied.
uploadHandler(file, headers?) ⇒ Promise<string>nullSpecifies the image upload handler (the second argument is headers).
videoUploadHandler(file, headers?) ⇒ Promise<string>nullSpecifies the video file upload handler (v2.7.5). When set, the [Video] dialog gets an [Upload file] tab and mp4 files dropped into the body are uploaded too. The returned server URL is inserted as <video controls>. Without it, file upload is unavailable — videos are never embedded as base64. See 2-1 Video upload.
video{ maxBytes?, accept? } | nullnullVideo upload limits (v2.7.5). maxBytes defaults to 200 MB and accept to ['mp4'] (you can add 'webm'; allowing mp4 also accepts m4v).
EquationsHangul equation script is rendered as HTML — fractions (over), super / subscripts, radicals, sized brackets (LEFT … RIGHT), operators, Greek letters, sum / integral signs. It uses inline styles only (no external CSS or images), so it is preserved in the saved HTML; the original script is kept in data-eq. Matrices (matrix, cases), factor ladders (LADDER) and long division (LONGDIV) are laid out as grids, and only equations that cannot be rendered fall back to a [equation: …] marker.
Multi-column layout (two-column exam papers)Each page becomes a table with one cell per column (top-aligned, with a rule between columns), so the left / right arrangement of the original is kept. Columns and pages are detected from the vertical positions in the line layout records even though the file records no page breaks. The editor’s table tools work on the cells.
imageStorageobject | nullnullSpecifies how images are stored (v2.6.6.2): { mode:'inline' | 'upload' | 'deferred', urlBase, storeUrl:'absolute' | 'asis', sameOrigin:'keep' | 'relative', onUploadFail:'keep' | 'remove', concurrency, export:'asis' | 'absolute' | 'embed', external:'keep' | 'import', onImportFail:'keep' | 'remove' }. A value of null keeps the current behaviour (base64 without a handler, immediate upload with one). Refer to §2-1-9.
importHandlerfunction | nullnullSpecifies the handler for remote image import (v2.6.7.1): (url, headers) => Promise<URL of the server copy>. It replaces an image on another domain with a copy your server fetched and saved. It is used when imageStorage.external is 'import', and when editing an external image with DEXT Image (it saves even when CORS blocks the original). Refer to §2-1-9.
imageUploadobject | nullnullSpecifies image insert limits: { allowTypes, maxFileSize, maxCount, messages }. They apply to files inserted via the dialog, drag & drop and paste; null means no limit. Refer to §2-1-10. v2.6.8
dragDropboolean | objecttrueSpecifies whether files can be dropped. false blocks all files, and { image: false, document: false } blocks them by kind. A blocked drop emits fileDropBlocked. v2.6.8
onBeforeImageAddfunction | nullnullSpecifies a function called right before an image file is inserted: (info) => boolean. Returning false skips that file. v2.6.8
pluginsstring[] | ObjectallSpecifies which plugins to enable. Word import requires 'wordimport' in the list.
preset (v2.6.8)'full' | Object—Specifies the one-line setup. 'full' = every built-in plugin + the optional plugins (import · Markdown · OCR · charts) + the menu bar. The order is defaults < preset < options you pass. To load the plugin files as well, use WebEditor.create. See 1-2 One-line setup.
toolbarArray | nullnullSpecifies a custom toolbar layout as an array of commands per row [[…],[…]], where '|' is a separator. Refer to 2-2.
menubarboolean | Arraytrue (false before v2.6.8)Specifies the top menu bar. true uses the default 8 groups (File…Help), an array defines a custom structure, and false hides it. Since v2.6.8 it appears by default; however, if you do not set it and hide the toolbar (toolbar as false or an empty array, e.g. a viewer), it does not appear. To keep the old look without a menu bar, pass menubar: false. Refer to 10-3.
onInitFunctionnullCalled when initialisation completes.
onKeyDownFunctionnullCalled on keydown (return false to block).
onKeyUpFunctionnullCalled on keyup.
onBeforeCommandFunctionnullCalled before a command runs (return false to block).
onTabChangeFunctionnullCalled when the tab changes (return false to block).
onMenuCommandFunctionnullCalled before a menu command runs (return false to block).
onLicenseValidFunctionnullCalled when a full licence verifies successfully.
onLicenseInvalidFunctionnullCalled when licence verification fails.
onErrorFunctionnullSpecifies the internal error callback (context, error). It is called together with the 'error' event (context such as 'uploadHandler' · 'docxImport' · 'profanity.load' · 'setLanguage'). See 4.
autoSaveObject | nullnullSpecifies automatic draft saving { interval, storageKey, scope, unloadWarning, unloadMessage, onSave, storage }. scope is the user / document part of the key, and storage is where drafts are kept ('localStorage' by default · 'indexedDB') (5-5).
storageInfoboolean | nullnullSpecifies whether the Browser storage window is available (Tools menu, ribbon, and the button in the auto-save failure notice). When not set, the menu and ribbon items appear only on editors with autoSave on. true always shows them, false hides all of them (5-5). v2.6.8
inlineToolbarboolean | string[]falseIndicates whether a floating mini toolbar is shown on text selection. With true it offers bold, italic, underline, link and clear formatting (the eraser icon); you can pick the buttons with an array ('bold', 'italic', 'underline', 'strikethrough', 'insertLink', 'removeFormat'). The mini toolbar closes with Esc or a click outside.
hyperLinkDefaultTarget'_self' | '_blank' | '_top' | '_parent''_self'Specifies the default target for new hyperlinks.
privacyObject | nullnullSpecifies personal-data detection { detect:[...], onDetect }.
profanityObject | nullnullSpecifies banned-word detection { words, onDetect, maskChar }. It uses the global window.WebEditorBannedWords instead when words is omitted.
guardObject | falsenullSpecifies the pre-submit check { notify, block, mask, scope, reveal }, which is used by guardBeforeSubmit(). Refer to 3-8, pre-submit check.
uploadHeadersObject | nullnullSpecifies custom headers for upload requests.
csrfCookiestring | nullnullSpecifies a cookie whose value is automatically sent as an X-CSRF-Token header.
evaluationWatermarkbooleantrueIndicates whether a watermark is shown behind the body in trial mode.
packNoticebooleantrueIndicates whether a notice bar is shown when an Extension feature (document import, charts, AI) is used with a Basic Pack subscription key. The packRestricted event fires either way (6-2-1). after v2.7.2.0

2-1. uploadHandler examples

Without an uploadHandler, images are stored inline as base64. If the images need to be stored on a server, please make sure to set one.

Order of operations — insert as base64 first, then swap in the URL once the upload finishes

Knowing this order will help you understand the examples below.

StepWhat happensEvent
①The image is inserted into the body immediately as base64 (the user sees it right away)imageInserted (src=base64)
②uploadHandler(file, headers) is called—
③ successimg.src is replaced with the returned URLimageUploaded (src=server URL)
③ failureThe base64 stays in place (nothing is lost) and onError('uploadHandler', err) fires—
Upload failures are silent. When an upload fails, the base64 remains and makes the body larger, so we recommend detecting it with the onError option or editor.on('error'), or checking whether data:image is still present in getHTML() right before saving (§2-1-6).
The second argument, headers, merges uploadHeaders with csrfCookie (→ X-CSRF-Token). Existing handlers that take a single argument keep working (backwards compatible).
Images that arrive by paste or drag may be a Blob rather than a File, so file.name can be missing. If you need a file name, please provide a fallback such as file.name || ('paste-' + Date.now() + '.png').

2-1-1. The basic form — upload FormData to a server API

new WebEditor('#editor', {
  uploadHandler: async (file) => {
    const form = new FormData();
    form.append('file', file);
    const res = await fetch('/api/upload', {
      method: 'POST',
      body: form
    });
    const data = await res.json();
    return data.url; // return the uploaded image URL
  }
});
The return value is the string that goes straight into <img src>. Absolute URLs (https://cdn…/a.png) and root-relative paths (/uploads/a.png) both work, and returning an empty string or null leaves the base64 in place.

2-1-2. When authentication or CSRF is required (using headers)

If you pass the headers argument straight through, your uploadHeaders and csrfCookie settings are applied automatically.

new WebEditor('#editor', {
  uploadHeaders: { 'Authorization': 'Bearer ' + token },
  csrfCookie: 'XSRF-TOKEN',   // cookie value → injected as the X-CSRF-Token header

  uploadHandler: async (file, headers) => {
    const form = new FormData();
    form.append('file', file, file.name || 'image.png');

    const res = await fetch('/api/upload', {
      method: 'POST',
      headers: headers,          // ⚠ do not set Content-Type (the boundary is added automatically)
      credentials: 'include',  // needed for session-cookie auth
      body: form
    });
    if (!res.ok) throw new Error('Upload failed: ' + res.status);
    return (await res.json()).url;
  }
});
If you set Content-Type yourself on a FormData request, the multipart boundary is lost and the server cannot parse it. If headers contains Content-Type, please remove it before passing it along.

2-1-3. Parsing responses from different server shapes

Each upload API responds differently. You only need to return a URL string, so you can simply adapt the part that extracts it.

// ① { "url": "https://cdn.example.com/a.png" }
return (await res.json()).url;

// ② { "data": { "path": "/uploads/2026/07/a.png" } } — a relative path works too
return (await res.json()).data.path;

// ③ a server that returns just the URL string in the body
return (await res.text()).trim();

// ④ a server that returns it in the Location header (REST 201 Created)
return res.headers.get('Location');

// ⑤ a server that returns only the file name → build the path on the client
const { filename } = await res.json();
return '/files/images/' + encodeURIComponent(filename);

2-1-4. Uploading straight to S3 or cloud storage (presigned URL)

The file goes straight to storage without passing through your server. This suits large files and reduces the load on your server. The server only issues a signed URL.

uploadHandler: async (file, headers) => {
  // ① ask the server for a presigned PUT URL
  const signRes = await fetch('/api/upload/presign', {
    method: 'POST',
    headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
    body: JSON.stringify({
      filename: file.name || 'paste.png',
      contentType: file.type || 'image/png',
      size: file.size
    })
  });
  if (!signRes.ok) throw new Error('presign failed');
  const { uploadUrl, publicUrl } = await signRes.json();

  // ② PUT directly to storage (do not add auth headers — they invalidate the signature)
  const putRes = await fetch(uploadUrl, {
    method: 'PUT',
    headers: { 'Content-Type': file.type || 'image/png' },
    body: file
  });
  if (!putRes.ok) throw new Error('Storage upload failed');

  // ③ return the public URL
  return publicUrl;
}
Without CORS configuration on the bucket (allowing PUT and your editor's origin), the browser blocks the request. Also, if you forward the auth headers from the presign request into step ②, signature verification fails.

2-1-5. Showing upload progress (XMLHttpRequest)

fetch cannot report upload progress. When you need to show progress, write a function that uses XMLHttpRequest and returns a Promise.

uploadHandler: (file, headers) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/api/upload');
  Object.entries(headers || {}).forEach(([k, v]) => xhr.setRequestHeader(k, v));
  xhr.withCredentials = true;

  xhr.upload.onprogress = (e) => {
    if (!e.lengthComputable) return;
    const pct = Math.round(e.loaded / e.total * 100);
    document.getElementById('upload-bar').style.width = pct + '%';
  };
  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
      resolve(JSON.parse(xhr.responseText).url);
    } else {
      reject(new Error('Upload failed: ' + xhr.status));
    }
  };
  xhr.onerror = () => reject(new Error('Network error'));

  const form = new FormData();
  form.append('file', file, file.name || 'image.png');
  xhr.send(form);
})

2-1-6. Validation, size limits, retries, and a pre-save check

We recommend blocking unsupported formats and oversized files before uploading, and retrying temporary errors. Throwing keeps the base64, so the user never loses their work.

const MAX = 5 * 1024 * 1024;              // 5MB
const ALLOW = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];

new WebEditor('#editor', {
  uploadHandler: async (file, headers) => {
    // ① validate — do not upload unless it passes
    if (!ALLOW.includes(file.type)) throw new Error('Unsupported format: ' + file.type);
    if (file.size > MAX)              throw new Error('The file exceeds 5MB.');

    // ② retry up to 3 times (exponential backoff)
    for (let i = 0; i < 3; i++) {
      try {
        const form = new FormData();
        form.append('file', file, file.name || 'image.png');
        const res = await fetch('/api/upload', { method: 'POST', headers, body: form });
        if (!res.ok) throw new Error('HTTP ' + res.status);
        return (await res.json()).url;
      } catch (e) {
        if (i === 2) throw e;                       // final failure → keep the base64
        await new Promise(r => setTimeout(r, 500 * Math.pow(2, i)));
      }
    }
  },

  // ③ tell the user it failed (do not let it pass silently)
  onError: (context, err) => {
    if (context === 'uploadHandler') alert('Image upload failed: ' + err.message);
  }
});

Check right before saving: Look for images whose upload failed or has not yet finished.

function hasPendingBase64(editor) {
  return editor.body.querySelectorAll('img[src^="data:image"]').length > 0;
}

saveBtn.addEventListener('click', () => {
  if (hasPendingBase64(editor)) {
    if (!confirm('Some images were never uploaded to the server. Save them inline in the body?')) return;
  }
  save(editor.getHTML());
});

// If you want to track upload completion with an event
editor.on('imageUploaded', ({ src, node }) => console.log('server URL settled:', src));

2-1-7. Comparing the storage approaches

ApproachWhat ends up in the bodyUpsideWatch out for
Inline base64
(no uploadHandler)
data:image/png;base64,…No server is needed, and the document is self-contained (offline use, email attachments).The body grows to roughly 1.33× the original. DB column limits and slower transfers can be a concern. Images cannot be cached.
Upload to a server API
(§2-1-1 · 2)
/uploads/a.pngThe body stays light, and images are cacheable and CDN-friendly. Access control is easy.It needs an upload API and storage, plus auth / CSRF handling.
Direct to storage
(§2-1-4)
https://cdn…/a.pngThere is no server load, which suits large files.You need to manage CORS and signature expiry. Please review how widely the public URL is exposed.
Cleaning up orphans: If the user deletes an image after it is uploaded, or never saves the post, the file remains on the server. We recommend sending the list of <img src> values along when saving, and periodically deleting files that nothing references.
Server-side validation is required. The format and size checks in uploadHandler can be bypassed in the browser. Re-validate MIME type, extension, and size on the server, and make sure scripts cannot execute from the upload path.

2-1-8. Downscaling images before upload (imageResize)

Uploading large photos as they are increases both the body size and your upload traffic. With imageResize on, only images wider than the limit are re-encoded at fewer pixels, with the aspect ratio preserved. The downscaled result goes into both the base64 in the body and uploadHandler.

new WebEditor('#editor', {
  imageResize: {
    maxWidth: 600,        // downscale only above 600px (anything smaller stays original)
    maxHeight: 0,         // 0 = no height limit
    quality: 0.85,       // JPEG / WebP re-encoding quality
    formats: ['image/jpeg', 'image/png', 'image/webp'],
    onLargerResult: 'original'   // use the original if the result is bigger
  }
});

// fires only when downscaling actually happened
editor.on('imageResized', (e) => {
  console.log(e.originalWidth + 'x' + e.originalHeight + ' → ' + e.width + 'x' + e.height,
              e.originalSize + 'B → ' + e.resizedSize + 'B');
});
PropertyDefaultDescription
maxWidth—Images are downscaled only above this width. They are never upscaled.
maxHeight0Specifies an optional height cap. Scaling follows whichever dimension needs to shrink more.
quality0.85Specifies the JPEG / WebP re-encoding quality (0–1). PNG is lossless, so it is unaffected.
formatsjpeg · png · webpSpecifies which MIME types get downscaled.
onLargerResult'original'Specifies which image is used when the result is larger than the original: the original ('original') or the resized one ('resized').
Please note that this is different from maxImageWidth, which caps only the displayed size (CSS); the uploaded file stays original. To reduce file size, use imageResize. The two options can be combined.
Re-encoding an animated GIF through a canvas leaves only the first frame. For this reason, GIF is not a default target, and even if you add 'image/gif' to formats, animated GIFs automatically keep the original (only static GIFs are downscaled).
The original MIME type is preserved, so PNG transparency survives. EXIF rotation on JPEG photos is applied too, so images do not end up sideways or flipped. If the browser does not support createImageBitmap / canvas.toBlob, or decoding fails, the original is used as-is.
Downscaling applies to file picker, paste, and drag-and-drop alike. It does not apply to images already in the body, or to images inserted by URL (insertImage(url)).

Document background images (documentBackground) also use the same uploadHandler once they exceed the threshold. Without one, they are embedded as base64, and a size warning is printed to the console.

2-1-9. Choosing how images are stored — imageStorage (v2.6.6.2)

Without this option, nothing changes: without an uploadHandler images are stored base64 inline, and with one the image is uploaded as soon as it is inserted. The modes below are chosen and set up by the developer. The goal is for an inserted image to go to the server and for the saved HTML to show it wherever it is opened.

ModeWhile editingimg src in saved HTMLVisible anywhere?
inline (default, no handler)base64base64Yes, but heavy files
upload (default with a handler)server URL (relative)relative URLOnly on the same site
upload + urlBaseServer URL (absolute)Absolute URL — the domain is baked into the post△ breaks if the domain changes
Recommended upload + storeUrl:'asis' + sameOrigin:'relative' + export:'absolute' (v2.6.8)Server URL (relative)Relative URL · absolute only in downloaded HTML○ keeps working on the site even if the domain changes
deferredbase64 + pending markeruploaded in one go by uploadPendingImages() right before saving → absolute URLYes, and almost no orphan files
Export policy export—asis · absolute · embed (server images pulled back in as base64 → self-contained file)Yes, combined with any mode
new WebEditor('#editor', {
  uploadHandler: async (file, headers) => { /* unchanged — return a URL string */ },
  imageStorage: {
    mode: 'upload',        // 'inline' | 'upload' | 'deferred'  (omitted: upload with a handler, inline without)
    urlBase: true,          // make relative URLs absolute. true = relative to this page, a string = that folder
    storeUrl: 'asis',      // (v2.6.8) keep the server's URL in the body | 'absolute' via urlBase (default when urlBase is set)
    sameOrigin: 'relative', // (v2.6.8) make this site's full URLs (paste · drag) relative | 'keep' (default)
    onUploadFail: 'keep',   // 'keep' the base64 (default) | 'remove' the image and notify
    concurrency: 2,         // parallel uploads for deferred
    export: 'asis'          // default image policy for File › Save, saveToHTML and getExportHTML
  }
});
Storing absolute URLs fixes the domain in the post. If the customer's domain changes, or one of the test · dev domains is retired, images in posts written on that domain break. We recommend keeping relative URLs in the body (storeUrl:'asis' · sameOrigin:'relative') and making only downloaded HTML absolute (export:'absolute'). Copying an image from the same site gives a full URL, so sameOrigin:'relative' rewrites it before saving (getHTML). Leave it off if your admin and public sites use different domains and you need full URLs on purpose. Normalising your own image URLs on the server at save time also covers posts that bypass the editor and older posts (JSP board sample: Web.relativizeOwnImages).

deferred — upload once, when posting. Images stay base64 while editing (marked data-we-pending="1") and are uploaded right before saving. getSafeHTML() removes the marker, so please use it whenever you save or send content.

saveButton.onclick = async () => {
  const g = await editor.guardBeforeSubmit();
  if (g && g.ok === false) return;
  const r = await editor.uploadPendingImages({ onProgress: (done, total) => status(done + '/' + total) });
  if (r.failed.length) { alert(r.failed.length + ' image(s) could not be uploaded.'); return; }
  form.body.value = editor.getSafeHTML();
  form.submit();
};
APIWhat it does
getPendingImages() → HTMLImageElement[]Returns images not yet on the server (base64): deferred ones, failed uploads, and pictures that came in through import (DOCX etc.) or paste.
hasPendingImages() → booleanReturns whether that list is non-empty, for use as a pre-submit check.
uploadPendingImages({ concurrency, onProgress }) → Promise<{ uploaded, failed }>Uploads pending images through uploadHandler and swaps the src. One undo step restores the state before the swap. It works in every mode (also to retry failed uploads).
toAbsoluteImageUrls(html?) → stringReturns the content (or the given HTML) with relative img src made absolute with urlBase.
getExportHTML({ images, format, css, title, embedMaxBytes }) → Promise<{ html, embedded, skipped, bytes }>Returns the same material as the saved file (viewer CSS + sanitized content) as a string. images:'embed' fetches server images and inlines them as base64 (other origins need CORS; anything that cannot be fetched is listed in skipped and left as is).
saveToHTML(name, { images })This is the existing function with an image policy. It defaults to imageStorage.export. 'embed' returns a Promise and downloads when done.
DEXT Image results and the document background follow the same mode. In inline and deferred an edit result comes back as base64 (and counts as pending); in upload it is uploaded and made absolute. For absolute-URL images to open outside the site, the server must serve them without authentication. Where that is not acceptable, you can make the file self-contained with export:'embed'.

Importing remote images — importHandler · imageStorage.external (v2.6.7.1)

Images on another domain — inserted by URL or pasted from the web — stay in the content as their original address by default. If the original site removes them, they disappear from the post, and edits made with DEXT Image cannot be saved when that server does not allow CORS. You can turn on external:'import' to replace them with a copy your server fetched and saved.

new WebEditor('#editor', {
  uploadHandler,
  importHandler: (url, headers) => fetch('/image/import', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...headers },   // same headers as uploads (incl. CSRF)
      body: JSON.stringify({ url }),
      credentials: 'same-origin'
    }).then(r => r.json()).then(j => { if (j.result !== 'success') throw new Error(j.code); return j.imageUrl; }),
  imageStorage: { mode: 'upload', urlBase: true, external: 'import', onImportFail: 'keep' }
});
Storage modeExternal images (external:'import')
uploadThe image is fetched through importHandler as soon as it is inserted, and then the src is replaced. On failure, onImportFail applies: keep leaves the original address, and remove removes the image and tells the user.
deferredThe image is only marked with data-we-external. It is listed by getPendingImages() and fetched by uploadPendingImages() together with uploads.
inlineThe image is not fetched (nothing is kept on the server).

Events: imageImportStart · imageImported({ src, sourceUrl, node }) · imageImportFailed({ node, sourceUrl, error }). Same-origin and data: images are not fetched. The original address is not kept in the document; it is reported only through the events. The default is external:'keep', so an update alone never starts copying other sites' images to your server.

On the server, SSRF protection is essential. The server requests an address it was given, so without these checks it could be used to read your internal network or cloud metadata (169.254.169.254). The bundled DEXT Image ships PHP · JSP · ASP.NET · ASP samples (server/*/import.*); the contract is chapter 24 of the DEXT Image integration API manual. With importHandler set, the DEXT Image editor also opens external images this way, so edits can be saved even when CORS blocks the original.

2-1-10. Image insert limits · drag & drop · deleted images — imageUpload · dragDrop · getDeletedImages() (v2.6.8)

Files inserted through the dialog (or file picker), drag & drop and paste all go through the same check, in this order: count → type → size → pre-insert check. A rejected file is not inserted; an imageRejected event is emitted and one grouped notice is shown. Images inserted by URL are not files and are not checked.

const editor = new WebEditor('#editor', {
  uploadHandler: myUpload,
  imageUpload: {
    allowTypes: ['jpg', 'png', 'gif', 'webp'],   // extensions or MIME ('image/*')
    maxFileSize: 10 * 1024 * 1024,            // 10 MB per file
    maxCount: 10,                              // 10 images at a time
    messages: { size: '{name} is over {limit}' }
  },
  dragDrop: { document: false },             // block dropping document files only
  onBeforeImageAdd: (info) => info.size > 0
});
ParameterDescription
allowTypesSpecifies the allowed types: extensions ('jpg' · '.png') or MIME types ('image/jpeg' · 'image/*'). jpg and jpeg are the same. If empty, all types are allowed.
maxFileSizeSpecifies the per-file limit in bytes. 0 means no limit.
maxCountSpecifies the number of images per action; any beyond it are not inserted. 0 means no limit.
messagesOverrides the notice text. { type, size, count } may use {name} · {size} · {limit} · {allowed} · {max} · {count}.

Blocking drops — dragDrop. false blocks every file; { image: false } · { document: false } block that kind only. If any dropped file is blocked, the whole drop is refused with a notice and fileDropBlocked({ files, blocked }) is emitted — you can use it to pass dropped files to your attachment uploader instead. Dragging text or HTML is never blocked.

Pre-insert check. If onBeforeImageAdd(info) returns false, or a beforeImageAdd listener calls preventDefault(), the file is not inserted. info is { file, name, size, type, source } with source one of 'dialog' · 'drop' · 'paste'. Files cancelled this way are not announced.

Deleted images — getDeletedImages(prefix). This returns the URLs of images that were in the body and have since been removed. You can use it when saving in an edit screen to clean up image files on the server. data: images (not uploaded yet) are not recorded, and setHTML() resets the baseline.

const gone = editor.getDeletedImages('/upload/');   // server images only
form.deletedImages.value = gone.join('\n');

Video upload — videoUploadHandler (v2.7.5)

Overview. Uploads the mp4 file the user picks to your server and inserts the returned URL into the body as a video with playback controls (<video controls>). The existing [URL] tab for YouTube · Vimeo · mp4 addresses is unchanged; the [Upload file] tab appears only when the handler is set.

PartDescription
[Video] dialog · [Upload file] tabPick a file, set width and alignment, and click [Insert]; the dialog closes and the upload starts.
Drag and dropAn mp4 dropped into the body is uploaded at the drop point. Several files are uploaded one after another.
editor.insertVideoFile(file)Uploads from code, inserts at the caret and resolves with the server URL (3-3).
Uploading placeholderAn "Uploading video…" box sits in the body and is replaced by the video on success. On failure the box is removed and a notice is shown (nothing is left in the body). The box never goes into the saved HTML.

Parameters. The handler has the same shape as the image uploadHandler.

ParameterDescription
fileThe video File. The editor checks the extension, size and file header (mp4 ftyp, webm EBML) before passing it on.
headersuploadHeaders merged with csrfCookie (→ X-CSRF-Token).
Return valueA Promise of the server URL string. Report failure by throwing (rejecting). javascript: · data: URLs are refused.

Configuration example

const editor = new WebEditor('#editor', {
  videoUploadHandler: async (file, headers) => {
    const fd = new FormData();
    fd.append('file', file);
    const r = await fetch('/video/upload', { method: 'POST', body: fd, headers });
    const j = await r.json();
    if (j.result !== 'success') throw new Error(j.message);
    return j.videoUrl;                       // e.g. /video/view?name=1731234567890-a1b2c3.mp4
  },
  video: { maxBytes: 200 * 1024 * 1024, accept: ['mp4'] }
});

Inserted HTML. The saved HTML contains the following. The viewing page needs no extra script.

<div class="we-video-wrapper" data-we-video="upload" style="…">
  <video controls preload="metadata" playsinline style="width:100%;display:block;" src="/video/view?name=…"></video>
</div>
Server requirements
  • HTTP Range (206) responses — the view URL must answer Range requests with 206 Partial Content and Content-Range, or seeking with the progress bar does not work. Safari (iOS) does not play URLs without Range support at all.
  • Format check — client checks can be bypassed. Check the extension and the file header on the server too (mp4: ftyp from byte 4), and send Content-Type: video/mp4 (without charset).
  • Size limits — set the server upload limit and the front web server limit (nginx client_max_body_size, Apache · WebtoB request body limit) to at least video.maxBytes.
  • Fast start — if the mp4 index (moov) is at the end of the file, playback starts only after the whole file is downloaded. Encode with -movflags +faststart.
  • Cleaning up unused files — videos upload the moment they are inserted, so files from posts closed without saving or removed from the body stay on the server. Collect the names used in bodies and delete the older rest.
The sample boards (JSP · Spring Boot) include /video/upload · /video/view (Range support) and the cleanup job.

Pre-submit check example. If you read the body before the upload finishes, the post is saved without the video. Check hasPendingVideos() in the submit button handler.

if (editor.hasPendingVideos()) { alert('A video is still uploading.'); return; }

2-2. UI config — build it on a settings page and apply it

Instead of hand-writing the toolbar, menu bar, and width, you can compose the UI visually on a settings page and save it as a config file. Refer to the settings hub, demo/settings.html.

Settings pageWhat it configuresConfig it produces
ui-config.htmlToolbar icons — visibility, order, placement across rows 1–3, group separators — plus menu bar on/off, status bar, and editor widthwebeditor-ui-config.js → window.DEEDITOR_UI_CONFIG
ui-config-apply.htmlAn example of applying a saved UI config to an editor
menubar-config.htmlThe dropdown menu bar — menus, items, order, separatorswebeditor-menubar-config.js → window.DEEDITOR_MENUBAR_CONFIG
menu-ui.htmlCompares and switches the menu UI template, classic ↔ ribbon (uiTemplate).

UI config format: It has the same shape as the initialisation options.

window.DEEDITOR_UI_CONFIG = {
  menubar: true,          // show the menu bar
  statusbar: true,        // status bar
  width: "100%",          // "100%" or a number (px)
  toolbar: [               // commands per row, '|' = group separator
    ["newDocument", "save", "|", "undo", "redo" /* …row 1… */],
    ["paragraphStyle", "fontFamily", "|", "bold" /* …row 2… */]
  ]
};

Applying it: Include the config file and pass it as options.

<script src="webeditor-ui-config.js"></script>
<script>
var cfg = window.DEEDITOR_UI_CONFIG || {};
var editor = new WebEditor('#editor', {
  menubar: cfg.menubar, toolbar: cfg.toolbar, plugins: [/* all */]
});
if (cfg.statusbar === false) editor.showStatusBar(false);
if (cfg.width) editor.setWidth(cfg.width);
</script>
The save button also writes to localStorage (deeEditor.uiConfig / deeEditor.menubarConfig). For every icon to appear, please load all of the relevant plugin bundles (including docbg, wordimport, and hwpximport). For details, see docs/04_API-development/UI_CONFIG_GUIDE.md.

2-2-1. Site config file (dee-editor.config.js) v2.6.8

One config file made by the administrator sets the defaults of every editor on the site. Load it before the editor bundle, and editors read it automatically when they are created, with no changes to page code.

The file is made with the admin settings tool (demo/admin-tool/index.html, Korean UI). The administrator opens it as a local file on their own PC (no server, no login, no network), checks the choices in a live preview editor, and downloads dee-editor.config.js plus banned-words.txt for the server. Opening the current file from the server shows what changed and the file fingerprint (SHA-256). An example page that only loads a file made with the tool is demo/site-config-sample.html (a minimal editor with no editor options in page code). The Korean package also ships a standalone folder dee-admin-tool/ (bundle copy and SHA256SUMS.txt) to copy to the administrator's PC.

<script src="/dee-editor/dee-editor.config.js"></script>   <!-- window.DEEDITOR_CONFIG -->
<script src="/dee-editor/dist/webeditor.js"></script>

// dee-editor.config.js — produced by the admin settings tool
window.DEEDITOR_CONFIG = {
  $schema: 'dee-editor-config', version: 1, generatedAt: '2026-10-11T10:00:00+09:00',
  options: {
    toolbar: [['undo', 'redo', '|', 'bold', 'italic']],
    imageUpload: { allowTypes: ['jpg', 'png'], maxFileSize: 10485760 },
    profanity: { words: ['company banned word'] },
    disablePlugins: ['video']
  }
};
ItemDescription
Orderdefaults < preset < site config < page options (new WebEditor(…, options)). Page options override them per screen. For approvalForm, autoSave and imageResize the page value is layered on the site value (site holidays stay when a page passes only part of it).
Level 1 — displaytoolbar, menubar, uiTemplate, iconTheme (name), height, width, placeholder, language, fonts, hyperLinkDefaultTarget, autoSave (no functions), approvalForm (holidays, weekend, input color), license, … Page options override them directly.
Level 2 — policyimageUpload, dragDrop, pastePlainText, privacy, profanity, guard, disablePlugins, ai (v2.7.1.1, 9-N-10) · chart (v2.7.3.0, 9-O-7): the stricter value applies. Image types must pass both lists, size and count limits take the smaller value, and banned words and privacy types are merged. A page cannot switch site checks off with privacy:false or guard:false. disablePlugins only removes plugins the code loaded.
Ignored keysKeys that turn protection off or load code or addresses (sanitizeOnLoad, stripScript, allowedTags, plugins, uploadHandler, importHandler, imageStorage, uploadHeaders, csrfCookie, contentCSS, iconThemePath, imageEditor, ocr, logoUrl, …), functions and on… callbacks, unknown keys and wrongly typed values are ignored with one console warning. Developers set those in page code.
Missing or broken fileNothing breaks; the editor starts with the code defaults.
License keyThe license in the config file takes precedence over the global keys in page code (WebEditor.defaultLicense, window.WebEditorLicense, webeditor-configuration.js), though not over the page option license. A wrong key or the localhost-only key (dextsolution) in the config file turns a correctly licensed site into evaluation mode. If page code already sets a key, please leave the config key empty. The admin settings tool warns about this on export.
Bundles before v2.6.8They do not read the config file (it is ignored without errors). A page whose key is only in the config file runs in evaluation mode. Check the version with WebEditor.version.
APIDescription
siteConfig optionomitted = window.DEEDITOR_CONFIG · false = do not read (e.g. the settings tool preview) · object = use it (same format as the file)
editor.getSiteConfig(){ source, meta, applied, rejected } — where it came from ('window', 'option', null), what was used and what was dropped (rejected: [{ key, reason }], reason = forbidden, unknown, type, function)
WebEditor.loadSiteConfig(url)Reads a same-origin JSON config into window.DEEDITOR_CONFIG (Promise). Other origins are refused. Editors created afterwards use it.
WebEditor.validateSiteConfig(cfg)Checks a config with the editor's rules and returns { options, rejected, meta }.
WebEditor.siteConfigKeys()Keys and levels [{ key, level }] (1 display · 2 policy · 3 forbidden)
The config file is a static file on the server, so only people with deploy rights change it. Browser-side checks can be bypassed, so the server must re-check upload limits, banned words and HTML cleaning with the same values. DEEDITOR_UI_CONFIG / DEEDITOR_MENUBAR_CONFIG from 2-2 keep working as before (page code passes them).

2-3. Document templates & table layouts (DeeDocTools)

Load the shared module doc-tools.js and call DeeDocTools.attach(editor), and File ▸ Template (document skeletons) and File ▸ Layout (table structures) appear in the menu. It is an opt-in module independent of the core, so if you do not load it, nothing changes.

<script src="dist/webeditor.min.js"></script>
<script src="doc-tools.js"></script>

const editor = new WebEditor('#editor', { menubar: true });
DeeDocTools.attach(editor);   // adds the File ▸ Template / Layout menu items
Templates are picked up automatically from HTML files in the templates/ folder. On static hosting where directory listing is blocked, generate templates/manifest.json with make-templates-manifest.js. For details, see docs/04_API-development/DOCUMENT_TEMPLATES.md.

3. Instance methods

Most setter methods return this, so they can be chained.

3-1. Content I/O

getHTML(options?) → string

Returns the editor body as an HTML string. If options.normalize v2.7.1.0 is true, normalize() runs before returning; false skips clean-up. If omitted, the normalizeOnGet option decides. options.structure also applies the structural fixes when cleaning up (default false). See 9-M.

const html = editor.getHTML();
// '<p>Hello</p><p>Nice to meet you</p>'
normalize(options?) → object v2.7.1.0

Cleans up redundant tags that do not change the look, such as empty spans, nested spans and ineffective styles that build up in the body, and returns the counts ({ styles, unwrapped, merged, removed, brs, wrapped, hoisted, zwsp, total }). Options are { structure, keepDefaults }. Table structure, paragraph formatting, images and data-* are kept unchanged. See 9-M for details.

const report = editor.normalize();
// report.total — number of fixes (0 when called again)
setHTML(html) → this

Replaces the editor body with the given HTML.

editor.setHTML('<p>New content</p>');
getText() → string

Returns the plain text with the HTML tags removed.

const text = editor.getText();
// 'Hello\n\nNice to meet you' — a blank line between paragraphs
appendHTML(html) → this

Appends HTML to the end of the body.

editor.appendHTML('<p>An appended paragraph</p>');
insertHTML(html) → this

Inserts HTML at the caret. If there is a selection, it is replaced.

editor.insertHTML('<strong>Bold text</strong>');
getSelectedHTML() → string

Returns the HTML of the current selection, or '' if nothing is selected.

const selected = editor.getSelectedHTML();
getSelectedText() → string

Returns the plain text of the current selection.

const text = editor.getSelectedText();
clear() → this

Empties the editor body completely.

editor.clear();
pasteFromClipboard() → Promise<boolean>

Pastes the clipboard contents at the caret (for menu, ribbon, and button clicks, via the async Clipboard API). It runs the same pipeline as Ctrl+V (plain text, Word / external HTML, Excel range selections, table cells, images, PowerPoint slides/shapes as a picture). It requires a secure context (HTTPS or localhost), a user gesture, and permission; where this is unsupported or denied, it shows the Ctrl+V hint and returns false. (The “Paste” icon in the menu and ribbon calls this method.)

btn.addEventListener('click', () => editor.pasteFromClipboard());

3-2. State control

setReadOnly(bool) → this

Turns read-only mode on or off. In read-only mode the wrapper gets the .we-readonly class and the toolbar, menu bar and ribbon (uiTemplate:'ribbon') are disabled together. Commands that change the content (new document, formatting, insert, undo, etc.) do not run even if a button is clicked from a script; only read commands such as save, print, view switching and copy are available.

editor.setReadOnly(true);   // read-only
editor.setReadOnly(false);  // editable
isReadOnly() → boolean

Returns the current read-only state.

if (editor.isReadOnly()) {
  console.log('The editor is read-only');
}
isModified() → boolean

Returns whether the content changed since the last setHTML() or resetModified() call.

window.addEventListener('beforeunload', (e) => {
  if (editor.isModified()) {
    e.preventDefault();
  }
});
resetModified() → this

Resets the modified flag.

editor.resetModified();
setHeight(height) → this

Changes the editor height. number (px), '500px', and '50vh' are all accepted. When you give an explicit height, the editor switches to a fixed height with vertical scrolling inside the body.

editor.setHeight(600);
editor.setHeight('80vh');
setFixedHeight(on) → this

Turns fixed-height mode on and off at runtime. true treats the current height as a fixed height, and overflowing content is reached through the body's vertical scrollbar; false goes back to treating height as a minimum so the editor grows with its content. This has the same effect as the fixedHeight initialisation option.

editor.setFixedHeight(true);    // fixed + internal scrolling
editor.setFixedHeight(false);   // off (grows with content)
getHeight() → number

Returns the current editor height in pixels, including the editor border (1px top and bottom).

const h = editor.getHeight(); // after setHeight(600) → 602 (border included)
setWidth(width) → this

Changes the editor width.

editor.setWidth('100%');
editor.setWidth(800);
getWidth() → number

Returns the current editor width in pixels, including the editor border (1px left and right).

setTab(index|name) → this

Switches the editor tab. Accepts a numeric index or a name ('edit' / 'html' / 'preview'; case-insensitive, aliases allowed).

indexnameTab
0'edit'Edit (WYSIWYG)
1'html'HTML source
2'preview'Preview
editor.setTab(1);          // show the HTML source
editor.setTab('preview');  // names work too
getActiveTab(asName?) → number | string

Returns the active tab. By default it returns an index (0 / 1 / 2); getActiveTab(true) returns the name ('edit' / 'html' / 'preview').

editor.getActiveTab();      // 0
editor.getActiveTab(true);  // 'edit'
showToolbar(visible) · showMenuBar(visible) · showStatusBar(visible) → this

Controls the visibility of the toolbar, menu bar, and status bar. (The menu bar is on by default since v2.6.8; menubar: false hides it from the start.)

editor.showToolbar(false);   // hide the toolbar
editor.showMenuBar(false);   // hide the menu bar

3-3. Images

Insert preview (v2.6.6.2) — in the toolbar [Insert image file] dialog, picking files or typing a URL shows the picture, name, format, width × height (px) and file size before anything is inserted, with the supported formats listed underneath. Several files can be inserted together with [Insert (n files)], and pictures wider than the imageResize limit get a "will be resized" note. Files are inserted only when you press [Insert].
Supported formats — PNG · JPEG · GIF · WebP · BMP · SVG · AVIF (any format the browser can display). The file picker lists image/* together with the extensions, so the files appear and can be selected even when the type is not registered in the OS (common for .webp). Drag-and-drop and paste recognise such files by extension when the MIME type is empty, and fill it in before calling uploadHandler (v2.6.6.2). Please add image/webp to the server's allow-list as well; the JSP and React board samples already include it. An inserted WebP opens as it is in image editing (DEXT Image 2.2, built in), and the edited result can be saved as WebP too — see 9-G-4-1. Automatic downscaling (imageResize) handles WebP as well (it is in the default formats).
insertImage(url, alt?) → this

Inserts an image by URL at the caret. base64 data URLs are supported too.

editor.insertImage('https://example.com/photo.jpg');
editor.insertImage('data:image/png;base64,...');
getImages() → string[]

Returns an array of every image URL in the body.

const urls = editor.getImages();
// ['https://...', 'data:image/png;...']
getDeletedImages(prefix?) → string[] v2.6.8

Returns the URLs of images that were in the body and have been removed. With prefix, only URLs starting with it are returned. Refer to §2-1-10.

const gone = editor.getDeletedImages('/upload/');
// ['/upload/2026/10/a.png']
Image alternative text (alt)

Click the image, choose "Alt text" in the action bar, and type a description. It is read aloud to people who cannot see the image; for decorative images, please leave it empty (WCAG 1.1.1).

Images inserted from a file start with an empty alt. The file name used to be filled in automatically, but a file name is a name, not content — a screen reader simply reads out KakaoTalk_20260803_112233.jpg. It was also included in getHTML(), so the local file name of the author reached every reader.

Any alt typed in the insert-by-URL dialog is kept. From code, pass it as the second argument of editor.insertImage(url, alt).

Image captions

Click an image, then toggle “Add caption” in the action bar. The image is placed inside a <figure> with a <figcaption contenteditable> attached.

<figure class="we-img-figure">
  <img src="...">
  <figcaption contenteditable="true">Caption text</figcaption>
</figure>
Image hyperlinks

Click an image, choose “Add / edit link” in the action bar, then set the URL and how it opens.

Open modes (4):

  • _self — same window (default; no target attribute is added)
  • _blank — new window (rel="noopener noreferrer" is added automatically)
  • _top — topmost window (breaks out of an iframe)
  • _parent — opens the link in the parent window.

DOM structure:

// without a caption
<a href="https://example.com" target="_blank" rel="noopener noreferrer" data-we-img-link="1">
  <img src="...">
</a>

// with a caption — <a> wraps only the <img>
<figure class="we-img-figure">
  <a href="..." data-we-img-link="1"><img src="..."></a>
  <figcaption contenteditable="true">Caption</figcaption>
</figure>

Security guards:

  • With _blank, rel="noopener noreferrer" is added automatically (this prevents tabnabbing and referrer leakage).
  • javascript:, vbscript:, and non-image data: URLs are blocked automatically.
  • target values outside the allowlist are changed to _self.
  • Clicking a linked image inside the editing area does not follow the link (links in the saved HTML still work normally).
insertVideoFile(file, opts?) → Promise<string> v2.7.5

Uploads a video file with videoUploadHandler and inserts it at the caret as <video controls>. Resolves with the server URL. Rejects without changing the body if the file fails the checks (err.reason: 'type' · 'empty' · 'size' · 'content') or is cancelled in beforeVideoAdd ('cancelled').

ParameterDescription
fileThe File to upload.
opts.width · opts.alignWidth ('640px', '100%' …, default '100%') and alignment ('left' · 'center' · 'right').
const url = await editor.insertVideoFile(input.files[0], { width: '640px', align: 'center' });
hasPendingVideos() → boolean v2.7.5

Returns true while a video is still uploading in the body. Check it right before submitting so the post is saved after the upload finishes.

3-4. Content sanitising

clearFormat() → this

Removes all formatting (tags and inline styles) from the selection.

editor.clearFormat();
clearCSSFormat() → this

Removes only inline CSS styles from the selection. Tags such as <strong> and <em> are kept.

editor.clearCSSFormat();
removeTag(tagName) → this

Removes a specific tag inside the selection while keeping its contents.

editor.removeTag('span');    // <span style="...">text</span> → text
editor.removeTag('strong');
Pasting from Hangul (HWP) v2.6.7.0

Content copied in Hancom Hangul (Ctrl+C) and pasted into the body (Ctrl+V) is tidied by the core so that it looks like the original. No option or plugin is needed (WebEditor.HwpPaste in the core bundle). Because it uses what Hangul places on the clipboard rather than opening a file, it works the same for .hwp, .hwpx and even HWP 3.0 documents. Please note that Hangul must be installed on the user's PC.

What is fixedDetails
Cell alignmentHangul writes paragraph styles as numeric classes such as p.12{…}, which browsers ignore, so cells whose alignment was defined only in those rules used to be left-aligned.
Table width · column widths · cell paddingOriginal column widths are fixed with <colgroup> (including form documents whose first row is merged). Cell padding and row height follow the original.
Narrow cells · alignment spacesText that slightly overflows a cell is fitted on one line as Hangul does (padding first, then letter spacing), and runs of spaces used for alignment are kept.
FontsHangul-only fonts (HCI Poppy and the like) get a fallback stack of the same family, so Latin letters and digits no longer look different from the Korean text.
Black cells · colour bands · headings that look like linksRemoves the black background that Hangul exports for "no fill" paragraphs, the paragraph fills and named ranges (<a name>) of documents that came from Excel.
PicturesHangul provides pictures only as file:// paths, so they used to be lost. They are now extracted from the RTF on the same clipboard and inserted as PNG (Chrome, Edge). Where the browser does not provide RTF, only the pictures are left out and a notice is shown.
EquationsHangul also passes equations as file:// pictures with no bitmap in the RTF, so they used to disappear. The editor finds the equation script in the original JSON at the end of the clipboard fragment and renders it with the same renderer as HWP import (fractions, scripts, radicals, brackets, matrices, ladders, long division …). Equations are matched to pictures only when the object count equals the picture count.
Pasted pictures are inserted as base64, the same as when pasting from Word. Vector-only shapes and charts have no bitmap on the clipboard and are not imported.
Pasting from MS Office (Word, Excel, PowerPoint)

Word and Excel put floating pictures and shapes into the clipboard HTML only as file:// paths. The core (WebEditor.OfficePaste) takes the originals from other parts of the same clipboard and cleans up the tables and markers Office adds for page layout. No option or plugin is needed.

What is adjustedDetails
Excel picturesThe original that Excel ships with each picture (o:gfxdata) is inserted. When Excel hands several pictures over as one, they are drawn together in their original places.
Word picturesThe originals (PNG, JPEG) are taken from the RTF on the same clipboard and inserted in document order (Chrome, Edge). The picture Word puts directly into the HTML is a 256-colour GIF copy reduced to display size, so its colours break up; it is replaced by the original when one is available (the display size stays as in Word). If the count does not match, no picture is guessed and a notice appears.
Word listsBulleted and numbered paragraphs become real lists (ul, ol). Sub-lists go inside their parent item and follow the marker style (● ○ ■, 1., a), i., 가., ㄱ.) and start number, so renumbering and Tab indenting work. Markers it does not recognise (such as ①) and numbered headings are left as they are.
Word underline and strikethrough stylesDouble, wavy and dotted underlines, underline colour and double strikethrough are carried over as text-decoration.
Word lines, text boxes, framesLines such as title underlines are redrawn with their length, weight and colour. Text in text boxes and frames stays in the body flow; the empty tables used to place them on the page are removed.
PowerPoint textBullets (●) on empty lines are not inserted.
Office classesClasses such as MsoNormal and xl65 are not kept in the saved HTML. The look is kept in inline styles.
A diagram drawn from several text boxes and lines (an org chart, for example) carries no picture data on the clipboard, so it is not pasted and a notice appears. If an Excel picture cannot be taken out, a notice suggests [Paste as image].

3-5. Runtime settings

setDefaultFont(fontName) → this

Changes the editor's default font at runtime.

editor.setDefaultFont('Arial');
editor.setDefaultFont('Noto Sans KR');
setDefaultFontSize(size) → this

Changes the editor's default font size at runtime (in pt).

editor.setDefaultFontSize(16);
setDefaultLineHeight(lh) · setEditorDefaults(opts) · getEditorDefaults() → this / object

Change the default line height, or set / read the default font, size, and line height together. Changes are reflected immediately in the toolbar's font, size, and line-height dropdowns. (The dropdowns show the actual value at the caret, or the default, and switch to your choice once you pick one.)

editor.setDefaultLineHeight('1.6');
editor.setEditorDefaults({ font: 'Georgia', fontSize: 16, lineHeight: '2' });
editor.getEditorDefaults();  // { font:'Georgia', fontSize:16, lineHeight:'2' }
setContentCSS(css) → this

Adds CSS rules inside the editing area.

editor.setContentCSS(`
  p { line-height: 1.8; }
  img { max-width: 100%; }
`);

3-6. Lifecycle

focus() → void

Focuses the editor.

editor.focus();
destroy() → void

Destroys the editor instance completely, restoring the DOM and removing event listeners.

editor.destroy();

3-7. Word · HWP · HWPX · XLSX · PPTX · PDF (Beta) import

Documents are imported one at a time. When several files are dropped onto the body, only the first document is imported and a notice lists the files that were skipped (the same applies when the extensions differ, because import modules never run at the same time). Dropping several images still inserts all of them. v2.6.7.0
When the returned Promise settles — the import methods (importWordFile · importHwpFile · importHwpxFile · importXlsxFile · importPptxFile · importPdfFile · importMarkdownFile · importDocumentFile) settle once the import has actually finished — after the content is inserted, after a failure has been reported, or after the user cancels the dialog or progress window. This means the line after await can read the content or lock it with setReadOnly(true).
A failure (corrupt, encrypted, wrong format) does not reject; it is reported with a notice toast and an 'error' event (context = 'docxImport' · 'hwpImport' · 'hwpxImport' · 'xlsxImport' · 'pptxImport' · 'pdfImport'). The Promise rejects only when importWordFile() is called without the plugin loaded. v2.6.8
Opt-in feature — to use it, load the matching bundle (wordimport-native.min.js · hwpximport-native.min.js · xlsximport-native.min.js · pptimport-native.min.js · pdfimport-native.min.js) alongside the core and list its name (wordimport, etc.) in plugins.
All of them convert in the browser with no external libraries or server, which suits air-gapped networks.
importWordFile(file) → Promise<void>

Imports a .docx File object into the editor.

// from a file input
document.getElementById('fileInput').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  if (file) await editor.importWordFile(file);
});

// from a drop event
dropZone.addEventListener('drop', async (e) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0];
  await editor.importWordFile(file);
});
importHwpFile(file, options?) → Promise<void> v2.6.7.0

Imports a Hangul binary .hwp (5.x) file (plugins:['hwpimport'] opt-in · bundle hwpimport-native.min.js). It is separate from the HWPX plugin — the formats differ (.hwpx = ZIP + XML, .hwp = OLE compound file + compressed records), so the engines and bundles are separate and you can load either one on its own. The unified "Import document" button, drag & drop and importDocumentFile() pick the module by file extension. Hangul does not need to be installed on the user's PC.

What is imported — text · character formatting (font, size, color, bold/italic/underline/strike, super/subscript, shading, letter spacing) · paragraph formatting (alignment, margins, first-line/hanging indent, spacing before/after, line spacing, numbering/bullets) · tables (merges, column widths, per-side borders, fills (solid, gradient — linear/radial-gradient — and image fills — background-image, kept inline as base64), cell padding, vertical alignment, nested tables, table captions, the position of tables pushed over with spaces or tabs) · pictures (JPG, PNG, GIF, BMP) · pictures placed behind / in front of text (seals, signatures) · grouped shapes and rectangles that contain text (title boxes — line, fill, rounded corners, shadow box) · page breaks · footnotes (collected at the end) · landscape documents · runs of spaces used for alignment.

A picture that overlaps text, such as a seal, is imported at its original coordinates as an ordinary <img> that takes up no room (a float). The text is not pushed aside and appears over the picture, and the picture can still be selected, moved or deleted in the editor. It is kept in the saved HTML as well.

OptionDescription
mode'cursor' (default) / 'append' / 'replace'
silenttrue converts and inserts immediately, without the options dialog.
imagesfalse keeps pictures as base64 instead of passing them to the upload handler (default true).
maxTableWidthTables wider than this (px) are scaled down proportionally.

Supported HWP versions

DocumentSupportBehaviour
HWP 5.0.x – 5.1.x (.hwp saved by Hangul 2002 · 2004 · 2005 · 2007 · 2010 · 2014 · NEO · 2018 · 2020 · 2022 · 2024)✅ SupportedBody, formatting, tables and pictures are imported, for both compressed and uncompressed files. Verified versions: 5.0.2.4 · 5.0.5.0 · 5.1.1.0 . Other 5.x files are read the same way, with any appended fields skipped based on record size.
HWP 5.x distribution documents (published read-only)△ text onlyThe body is encrypted, so only the document's preview text is imported, with a notice saying so.
HWP 5.x password-protected❌Import stops with "password-protected documents cannot be opened". Please remove the password in Hangul, save the file, and try again.
HWP 3.0 or older (.hwp saved by Hangul 97 and earlier)❌These files use a completely different structure. They are recognised, and the user is asked to re-save them in Hangul (.hwp or .hwpx) or to copy and paste from Hangul; pasting works for 3.0 documents too.
HWPX (.hwpx) · an HWPX file named .hwp—.hwpx goes to hwpximport. For an HWPX file with a .hwp extension, the user is asked to "rename it to .hwpx".
HWP 6 or any other major version❌Import stops with "unsupported HWP version" and shows the version number.
Objects that are not imported — shapes without text (lines, ellipses, polygons) · charts · OLE objects that hold no bitmap · WordArt · headers/footers · pictures browsers cannot draw (WMF, EMF, TIFF). The notice after import lists how many objects were skipped.
Unreadable documents never fail silently. Hangul 97 (3.0) files, password-protected files and non-HWP files stop with an explanation. Distribution (read-only) documents and structurally damaged files import the document's preview text only, and say so. Equations, shapes without text and headers/footers are not imported; a notice lists how many objects were skipped. To convert without an editor, use HwpImportPlugin.convert(arrayBuffer), which returns { html, warnings, info, previewOnly }.
Known issue — on some PCs the file dialog for a folder containing .hwp files closes by itself (a shell extension from older Hancom Office). For the workaround and fix, see 9-I-8.
This product was developed with reference to the HWP document file format specification published by Hancom Inc.
importHwpxFile(file, options?) → Promise<void>

Imports a Hangul .hwpx file into the editor (opt-in via plugins:['hwpximport']). It converts tables (merged cells, borders, solid / gradient backgrounds, width / height, vertical alignment), text (alignment, line spacing, bold / italic / underline, colour, size), images, vector shapes (SVG), symbol fonts (PUA), dotted TOC leaders, and page breaks (details in §9-A). Equations, headers / footers, and footnote bodies are not supported; their text is preserved and a warning is shown. Binary .hwp files are imported by the separate hwpimport plugin (importHwpFile, above).

OptionDescription
modeSpecifies how to insert: 'cursor' (default) / 'append' / 'replace'.
silentIndicates whether the file is converted and inserted immediately, with no dialog.
maxTableWidthTop-level tables wider than this (px) are scaled down proportionally. Narrower tables keep their original width. When unset, the content width of the original page is used. It is not applied to nested tables.
showLogIndicates whether conversion warnings are shown.
const editor = new WebEditor('#editor', { plugins: ['format', 'table', 'hwpximport'] });
await editor.importHwpxFile(file, { mode: 'replace', maxTableWidth: 740 });
importXlsxFile(file, options?) → Promise<void>

Converts an Excel .xlsx file into HTML tables (<table class="we-xlsx-sheet">) and imports it (opt-in via plugins:['xlsximport']). It reflects grid reconstruction (filling empty cells and rows), merges, formatting (bold, font colour, solid backgrounds, distinguishable borders, horizontal alignment), fonts (family, size, bold, italic, underline), number formats (date / currency / percentage / thousands / decimal places), text overflow (spreading into empty cells, and wrapping when it still does not fit, so text is never clipped), column widths and row heights, and multiple sheets (details in §9-C). Formulas show their cached results (only =TODAY()/=NOW() and day offsets built on them are recalculated to today).

OptionDescription
mode'cursor' (default) / 'append' / 'replace'
silent · showLogIndicate, respectively, whether the dialog is skipped and whether conversion warnings are shown.
maxTableWidthSpecifies the maximum table width per sheet (px).
allSheetsIndicates whether every (non-hidden) sheet is converted (default true). false converts the active sheet only.
sheetsSpecifies sheet names (overrides allSheets; workbook order is preserved).
sheetSeparator'heading' (default) / 'pagebreak' / 'hr'
includeHiddenIndicates whether hidden sheets are included (default false).
const editor = new WebEditor('#editor', { plugins: ['format', 'table', 'xlsximport'] });
await editor.importXlsxFile(file, { mode: 'replace', maxTableWidth: 740 });
importPptxFile(file, options?) → Promise<void>

Renders a PowerPoint .pptx file as absolutely positioned HTML per slide (<div class="we-pptx-slide">) and imports it (opt-in via plugins:['pptimport']). It reflects vector shapes (prstGeom / custGeom → SVG), fills and outlines (including theme references), theme colours with alpha, tables, charts (pie / doughnut / bar / line as SVG), images (srcRect cropping, EMF approximation), and inherited placeholder colours and sizes, preserving the original layout (details in §9-D).

OptionDescription
modeSpecifies how to insert: 'cursor' / 'append' / 'replace' (non-silent defaults to replace).
silent · showLogIndicate, respectively, whether the dialog is skipped and whether conversion warnings are shown.
slidesSpecifies an array of slide numbers to import (1-based). If unset, all slides are imported.
allSlidesIndicates whether all slides are imported (default true).
const editor = new WebEditor('#editor', { plugins: ['format', 'image', 'table', 'pptimport'] });
await editor.importPptxFile(file, { allSlides: true });
Browser requirement: DecompressionStream support (Chrome / Edge 80+, Firefox 113+, Safari 16.4+). Each slide consists of .we-pptx-slide-title and .we-pptx-slide elements, which the preview (doc-preview.html) uses as slide tab anchors.
importPdfFile(file, options?) → Promise<void> new in v2.6.7 Beta

This is a Beta feature; what this means is explained in 9-J. Imports a PDF .pdf file as editable content (opt-in via plugins:['pdfimport'] · pdfimport-native.min.js). A PDF has no paragraphs, only coordinates, so the text fragments are rebuilt into lines → paragraphs, headings (by size), lists (bullets and numbers), tables (ruled grids with merged cells) and images. Two-column text is read column by column, and repeated headers, footers and page numbers are removed. Scanned pages become images. The parser is in-house (no external libraries) and opens documents with an open password or permission password (RC4, AES-128/256). What the separate product DEXT-PDF adds is described in 9-J-0.

OptionDescription
modeSpecifies how to insert: 'cursor' / 'append' / 'replace' (non-silent defaults to replace).
silent · showLogIndicate, respectively, whether the dialog is skipped and whether conversion warnings are shown.
pagesSpecifies an array of page numbers to import (1-based). If unset, all pages are imported. In the dialog, enter it as "1-5, 8".
importModeSpecifies the import mode: 'auto' (default: text pages as content, scanned pages as images) · 'text' (text only) · 'image' (page images — Type 1 only for scanned pages where the whole page is one image, Type 2 for every page). If there is no page image to insert, the body is left unchanged and the reason is shown (v2.6.8).
pageBreaksIndicates whether a page break is inserted between pages (default false: off, so paragraphs that span pages are joined).
headerFooterIndicates whether repeated headers, footers and page numbers are removed (default true).
passwordSpecifies the open password. If omitted, the user is asked for it when needed.
engineSpecifies the conversion engine: 'auto' (default) · 'native' = PDF Type 1 (built-in engine) · 'dext-pdf' = PDF Type 2 (DEXT-PDF 0.4.1+ structure analysis, available when the dext-pdf/ runtime is present). With Type 2, DEXT-PDF lays out paragraphs, headings, lists and tables; every page can be inserted as an image and unreadable pages are replaced by page images. With a 0.3.0 runtime, Dee lays out the text fragments itself. 'auto' picks Type 2 when the runtime is found. The editor option pdfImport: { engine, dextPdfUrl } sets the default and location. 'type1' · 'type2' · 'both' mean the same.
Global settingThe global configuration file (webeditor-configuration.js, loaded before the bundle) can set the engine for the whole site: window.WebEditorPdfImportEngine = 'type1' | 'type2' | 'both'. 'type1' uses the built-in engine only (the runtime is ignored and Type 2 is not offered in the dialog) · 'type2' uses DEXT-PDF only (it needs the dext-pdf/ runtime and reports an error when it is missing) · 'both' (default) uses Type 2 when the runtime is present and makes it selectable in the dialog's "Conversion engine". The precedence is: engine of importPdfFile > editor option pdfImport.engine > global setting > 'both'.
const editor = new WebEditor('#editor', { plugins: ['format', 'image', 'table', 'pdfimport'] });
await editor.importPdfFile(file, { importMode: 'auto', pageBreaks: false });

Forms and certificates v2.6.7.0

What the document looks likeWhat is imported
A form drawn with ruled lines (tax forms, application forms, receipts)The grid is imported as a table (merged cells, column widths, shaded cells, amounts right-aligned). With Type 2, when DEXT-PDF's structure analysis does not return that page as a table, only that page is rebuilt by Dee from DEXT-PDF's text fragments and ruled lines. A page with a border and one small table, or a page with only blank lines, is not affected.
Small boxes standing on their own inside a large cell (the "year" and "resident / non-resident" boxes in a form header)They become nested tables inside the parent cell, laid out side by side as box · title · box, so the title and the boxes' text no longer run together in one cell. (Type 1 and Type 2)
Cell borders vs. blank underlinesOnly a free-standing underline such as "Contact: ____" is read as a blank. A horizontal line whose end touches a vertical line is a cell border and is not turned into a blank. (both)
A pale background picture in the middle of the page (a certificate's seal watermark, letterhead wash, a scan with recognised text)With Type 2 (DEXT-PDF 0.4.8+) it is left out of the content and reported as a background image that was removed. DEXT-PDF decides this based on whether the page's text is set on top of it. Size alone cannot distinguish it from a real figure, so with Type 1 it is imported as a picture.
"Label : value" linesWith Type 2 (0.4.8+) each item gets its own line instead of running on in one paragraph. Fragments that contain only ':' are removed, and where only part of a page is set in two columns, the right-hand column is placed right after the left-hand item beside it.
Which engine? — certificates, documents with a background picture and documents with highlighted text come out better with Type 2 (DEXT-PDF runtime dext-pdf/ 0.4.8+). Without the runtime, Type 1 works as before. You can switch engines in the dialog's "Conversion engine" to compare.
Limitations: text in legacy CID fonts without a ToUnicode map, or in Type3 fonts, cannot be read, so those pages are skipped with a warning, or inserted as an image when the page has one. JPX, JBIG2 and CCITT images are not transferred. Tables without ruling lines come in as paragraphs. Vector shapes and charts are not imported. The wrapper is <div class="we-pdf-doc">, tables are .we-imported-table.we-pdf-table, scanned pages are figure.we-pdf-page.
importDocumentFile(file, options?) → Promise<void>

Imports a file by branching on its extension — .docx → importWordFile, .hwp → importHwpFile, .hwpx → importHwpxFile, .xlsx → importXlsxFile, .pptx → importPptxFile, .pdf → importPdfFile, .md → importMarkdownFile (only for plugins that are loaded). A format that cannot be imported is reported with a warning notice toast that lists the formats of the loaded plugins (rather than a blocking alert). The unified “Import document” button and menu item use this method. The default is importMode:'unified' (a single button); switch to 'individual' to show one button per format.

new WebEditor('#editor', {
  plugins: ['wordimport', 'hwpximport', 'xlsximport', 'pptimport'],
  importMode: 'unified',   // one unified 'Import document' button (default)
});
await editor.importDocumentFile(file);   // branches on the extension

3-8. Document safety, output, and UI control

isEmpty() → boolean

Returns whether the body is empty. Whitespace, &nbsp;, and empty paragraphs (<p><br></p>) count as empty; images, tables, and media make it false.

getSafeHTML(options?) → string

Returns HTML with XSS vectors removed. This is separate from getHTML(); we recommend using this one for saving or transmitting. When called without options, it removes only dangerous constructs; when you pass the allow lists below, it works as an allow-list sanitiser.

What the default (stripScript:true) removes hardened in v2.6.6.1

  • Tags — script style iframe frame object embed applet link meta base are removed together with their content.
  • Event attributes — every attribute starting with on is removed.
  • URL attributes — href src xlink:href action formaction poster srcdoc srcset and other URL-bearing attributes whose value is javascript:, vbscript: or data: (images excepted). Control characters are removed before the check, as browsers do, so java&#9;script: cannot slip through.
  • Inline style — only declarations containing expression(), behavior, -moz-binding or url(javascript:); the rest of the style is kept.
  • SVG <set>/<animate> elements that would swap in an href or event later are removed.
  • target="_blank" links always get rel="noopener".
OptionBehaviour
allowedTags: string[]Specifies the allowed tags (lower case). Anything else is unwrapped: the text is kept, but the tag is not.
allowedAttrs: string[]Specifies the allowed attributes; others are removed. If style is left out, inline styles are removed entirely.
allowedStyles: string[]Specifies the CSS property names kept inside style. Use it to prevent CSS injection such as a position:fixed overlay.
imageRewriter: (src) => stringCalled to rewrite image src, for example from base64 to a server URL.
stripScript: falseTurns off the removal of dangerous constructs (not recommended).
const safe = editor.getSafeHTML({
  allowedTags:   ['p','br','strong','em','a','img','table','tbody','tr','td','span'],
  allowedAttrs:  ['href','src','alt','colspan','rowspan','class','style'],
  allowedStyles: ['color','background-color','font-weight','text-align'],
  imageRewriter: (src) => src.startsWith('data:') ? uploadAndGetUrl(src) : src
});

Alongside a corporate XSS filter — browser-side sanitising can be bypassed with a direct POST, so the server filter is the last line of defence. Send getSafeHTML(), sanitise again on the server before storing, and serve the reading page with a CSP (script-src 'self'). The server allow list must keep Dee's class="we-*", the data-shape, data-youtube-id and data-we-* attributes and the svg elements used by shapes; otherwise, tables, shapes and videos will not display correctly. YouTube embeds are stored as <div class="we-yt-lite" data-youtube-id> with no iframe, so the server can safely remove every iframe.

Loading is sanitised too (v2.6.8) — setHTML() · insertHTML() · appendHTML() · the HTML source tab · the DOM API (setHTML · append · insertBefore …) · document import at the cursor sanitise HTML before it enters the body, with the same rules as getSafeHTML() (option sanitizeOnLoad, default true). The body is part of the page, so an <img onerror> in a stored post would otherwise run the moment it is loaded. Formatting · tables · images · <style> · data-* attributes are kept, and ordinary documents go in without re-parsing. A YouTube player started while editing (iframe) is turned back into its thumbnail. Saving and sending still use getSafeHTML() plus server-side sanitising.

For HTML you put on a page without an editor (a reading page, for example), WebEditor.sanitizeHTML(html, { stripStyleTags, noopener }) applies the same rules. To restore the old behaviour, use new WebEditor('#ed', { sanitizeOnLoad: false }).

Tag clean-up (v2.7.1.0) — getSafeHTML({ normalize: true }) cleans up redundant tags in the body before sanitising (same meaning as normalize on getHTML(); if omitted, the normalizeOnGet option decides). To clean up stored content in bulk, use WebEditor.normalizeHTML(html, { editor }). See 9-M.

Auto-save API

Available when the autoSave option is enabled: getAutoSaved() → string | null (for recovery), clearAutoSaved(), and saveNow() (saves immediately). With storage: 'indexedDB', restore with getAutoSavedAsync() (5-5). When browser storage runs out it clears its own older copy and tries once more; if that fails it puts the older copy back and notifies the user once (until the next successful save). The host page receives the autoSaveFailed event. [View storage] in the notice shows usage and lets the user delete old drafts (5-5).

const editor = new WebEditor('#editor', {
  autoSave: { interval: 30000, unloadWarning: true }
});
const saved = editor.getAutoSaved();
if (saved) { editor.setHTML(saved); editor.clearAutoSaved(); }
saveToHTML(filename?, opts?) → void

Downloads the content as an HTML file. The toolbar [Save] button and File › Save / Save As all use this method. A name with an extension is used as given; anything else falls back to document.html. The modified flag is cleared afterwards.

The saved file is built from the same parts as a viewer page v2.6.6.1 — the viewer stylesheet (webeditor-content.css) goes in as a <style> block and the content sits inside <div class="we-content">, so the file opens looking like the editor (previously the file was <body> + content only, which lost table cell padding, Excel column widths and the default font and line height). The content is getSafeHTML() output, so scripts are removed.

  • Using it on another site — you only need to move two blocks: the <style> and the <div class="we-content">. Every rule is scoped under .we-content with no !important or id selectors, so nothing else on the site is touched and the site can override anything. The comment at the top of the file repeats these instructions.
  • Simplifying — the <style> is split into sections [A]–[F], each saying what it does and what changes if you delete it. You can remove any sections you do not need. [A] base formatting · [B] paragraphs and headings · [C] tables and Excel · [D] imported documents · [E] code, quotes, shapes · [F] your contentCSS (only when given)
editor.saveToHTML();                                    // complete document (default)
editor.saveToHTML('post.html', { format: 'fragment' });  // <style> + wrapper only — for a CMS HTML field
editor.saveToHTML('post.html', { css: 'minimal' });      // sections [A]·[B]·[C] only
editor.saveToHTML('post.html', { standalone: false });   // legacy: <body> + content only
printDocument({ title }?) / printHTML(html, { title }?) / previewDocument({ title }?) → void

title becomes the PDF file name v2.6.6 — browsers take the default "Save as PDF" file name from the document title. When you pass editor.printDocument({ title: 'APR-2026-0001' }), it becomes the print document's <title>; for hidden-iframe printing the host page title is changed for the duration of the print as well (and restored afterwards). Without it, the localized default title is used.

Prints the content. The toolbar [Print] button, File › Print, the ribbon and Ctrl+P all use this method, so they produce the same result. It prints through an off-screen hidden iframe, so no blank window flashes. The print document carries A4 margins (@page), the document background, and the rules for spreadsheet tables, shapes and imported documents (HWPX, DOCX), plus page-break handling. The editor's default formatting (defaultFont, defaultFontSize, defaultLineHeight) is applied to the print as well v2.6.8 — unformatted text prints at the same size and line spacing as on screen (previously it was enlarged to 14px · 1.6). Paper and margins are WebEditor.PRINT (A4 · 12mm); the printable text width is WebEditor.printTextWidthPx() (≈703px). If the HTML tab holds edited source, that source is printed — what you see is what prints. printHTML(html) prints arbitrary HTML with the same formatting.

previewDocument() shows the very document printing produces in a new window, laid out as a sheet of paper (File > Print preview). The paper look is screen-only, so pressing Ctrl+P in that window prints exactly the same result. It returns null when the popup is blocked.

Sheets wider than the paper are scaled down to fit — an imported sheet keeps its original column widths in px, so anything past the A4 printable width (703px) used to be cut off (a stamp floating at the right edge was a typical case). The width is measured including floating images, and printing waits until images and fonts have settled.

Manually inserted page breaks are honoured in print v2.6.6 — the print document does not load editor.css, so the .we-page-break rule (toolbar insertPageBreak) is now included there. Previously, breaks that appeared on screen were lost in print.

saveToPDF(options?) / saveToPDFInWindow(options?) → void

Prints just the body through the browser print dialog (guiding the user toward “save as PDF”). It takes { title, hideToolbar, css }. saveToPDFInWindow renders the body into a new window and prints from there (higher quality). Wide Excel sheets are fitted to the paper on [Save as PDF] too v2.6.6 — right before printing, table.we-xlsx-sheet is scaled to the A4 print width and the screen is restored afterwards. Previously only [Print] did this, so the right edge was cut off only when saving as PDF.

setZoom(ratio) / getZoom() → this / number

Zooms the editing area (0.25 – 4.0; values outside that range throw a RangeError). It fires the zoom event and uses Chrome's zoom, falling back to transform: scale() in other browsers.

validate() / maskSensitiveData() / reviewSensitiveData() → Promise

These methods check and mask content according to the privacy and profanity options. validate() → { profanity, privacy }; maskSensitiveData() → the number of items masked across the body. Besides the visible text, link addresses (mailto: · tel: · sms:), image alt text (alt) and tooltips (title) are checked and masked too.

reviewSensitiveData() shows the results in a dialog: a list of type and content (8 per page, with previous / next), and per-item or select-all checkboxes so only the chosen items are masked. Overlapping types are reconciled automatically. It is also available from the 🛡 toolbar button and Tools › Content & privacy check in the menu.

const r = await editor.validate();   // { profanity:[...], privacy:[...] }
await editor.maskSensitiveData();      // mask everything in the body
await editor.reviewSensitiveData();    // results dialog (selective masking)

Korean business registration numbers (biz-no) are told apart from bank account numbers. Both have the same number of digits (123-45-67890 matches either), so the check digit (the last digit) decides. 220-81-62517 is reported as a business registration number; 220-81-62518, whose check digit does not agree, stays a bank account number. Ten digits written without separators are also matched, but there the check digit is the only evidence, so roughly one in ten arbitrary ten-digit numbers will match by chance.

WebEditor.ContentGuard.isBizNo('220-81-62517');  // true — separators optional

Korean corporate registration numbers (corp-no) are told apart from resident registration numbers. These two share the same shape exactly — both are 13 digits written 6-7, so the digit count alone cannot tell them apart. What separates them is the check-digit scheme: resident numbers use modulus 11, corporate numbers modulus 10. When a value satisfies both, it is left as a resident registration number, the more sensitive reading.

Corporate numbers issued from 31 January 2025 cannot be verified. A Supreme Court rule change extended the serial from six digits to seven, taking over the check-digit position, so there is no longer anything to verify. Those numbers are not reported as corporate registration numbers. Numbers issued before that date, which make up the great majority in circulation, are still reported.

WebEditor.ContentGuard.isCorpNo('110111-1129497');  // true

Resident registration numbers carry a check digit too, and the October 2020 change to the numbering scheme left it in place. Detection does not depend on it, however: a number that was mistyped or partly redacted still looks like personal data, and missing one is worse than reporting it. Instead, the result is included in each finding as verified, and the results dialog shows it beside the type. Business and corporate numbers are different — they share their shape with other kinds, so only values that satisfy the rule are reported as such.

const r = await editor.validate();
r.privacy; // [{ type:'ssn', value:'900101-1234567', verified:false }, …]
           //    verified is null for kinds with no rule to check

Passport numbers (passport) and Korean driver's licence numbers (driver-license) have no rule to check against — a passport number carries no check digit, and the licence number's eleventh digit is a checksum whose formula is not published. Both are matched on shape alone and always report verified: null.

Because there is nothing to verify, the shapes are kept narrow. A passport number must begin with one of the six type letters (M S R O D T), which excludes order codes such as X12345678; both the older M12345678 and the 2021 M123A4567 forms are matched. A licence number must carry its separators (11-22-333333-44), because a bare run of twelve digits is indistinguishable from a parcel tracking number. Licence numbers take precedence over bank account numbers, which match the same shape.

scanSensitiveText(text) / maskSensitiveText(text) v2.7.1.1

Checks text outside the body (such as text about to be sent elsewhere) with the same rules as the body's personal-data check (privacy.detect, the allow list, privacy.strict). scanSensitiveText() returns [{ type, value, label, masked, verified, strict }] (each value once) and maskSensitiveText() returns a copy with letters and digits masked and separators kept. Banned words are not checked. The AI writing check before sending (9-N-5) uses these methods.

const found = editor.scanSensitiveText('Contact 010-1234-5678');   // [{ type:'phone', label:'Mobile number', masked:'***-****-****', … }]
const safe  = editor.maskSensitiveText('Contact 010-1234-5678');   // 'Contact ***-****-****'
Checking before submit — guardBeforeSubmit()

Checks the body right before a post is submitted and, when something is found, shows a banner above the body. Masking can be handled from there.

The editor cannot know when a post is submitted, because the submit button belongs to your page. So this is offered as a call you make just before saving. If you do not call it, nothing about the existing behaviour changes.

async function savePost() {
  const r = await editor.guardBeforeSubmit();
  if (!r.ok) return;        // blocked — the banner is already up

  // masking may have changed the body, so read it after the check
  const body = editor.getHTML();
  // ...save...
}

Return value

FieldTypeDescription
okbooleanfalse means you should stop the submit (block:true and something was detected).
itemsArrayLists the detected entries as { type, value, masked, start }. Repeated occurrences of the same value are combined into one.
countsObjectHolds the counts per kind as { profanity, privacy }.

The guard option

OptionValuesDefaultDescription
notify'banner' · 'notice' · 'both' · false'banner' The banner sits above the body and lists each entry; the notice is a toast that only reports counts.
blockbooleantrue false only displays the result and returns ok:true, so it acts as a warning that still allows the submit.
mask'confirm' · 'off''confirm' Indicates whether the banner offers [Review & mask]. Nothing is masked automatically; the author confirms first, so text is never changed without their knowledge.
scope'all' · 'profanity' · 'privacy''all' Specifies what the pre-submit check looks at. The shield icon (manual check) is unaffected.
reveal'float' · 'scroll' · 'both' · false'float' Specifies how to alert when the banner is scrolled out of view. When [Submit] is pressed below a long post, the banner may be far above the visible area. 'float' shows a bar fixed to the viewport, 'scroll' scrolls to the banner, 'both' does both, and false turns it off. If the banner is already on screen, nothing extra happens.

Passing guard: false skips the check entirely and always returns ok:true.

How the banner behaves

  • The banner is drawn outside the body (contenteditable), so it never appears in getHTML() and cannot affect what you save.
  • Clicking an entry jumps to that spot in the body and selects the text.
  • [Review & mask] opens the existing results dialog, where entries are masked one by one. Afterwards the check runs again and the banner disappears once nothing is left.
  • Masking can be undone with Ctrl+Z.
  • If the banner is off-screen, a bar fixed to the viewport appears alongside it (reveal); [Show me] takes you to the banner, and the bar disappears by itself once the banner is visible.
  • A detection also fires a 'guard' event, for when you want your own notice next to the submit button: editor.on('guard', r => { if (r.blocked) myBadge.show(r.counts); })
  • Dismiss with ✕ or Esc, or call editor.clearGuardNotice().

⚠️ Note: only the body is checked. The editor has no access to page fields such as title or author, so please check those yourself if needed. Also, ok:false is only a signal; the calling code is responsible for actually stopping the save, as in the example above.

Configuring the banned-word list

Privacy detection works without any configuration — the patterns are built into the core. Banned words are different: the list varies by project and language, so the core ships none. Without a list, nothing is flagged.

The list can come from two places, and the editor option takes precedence over the global setting (the same rule as the licence key).

WhereScopeUse for
options.profanity.wordsOne editor instanceUsed for a screen that needs a different list.
window.WebEditorBannedWordsWhole siteUsed for a separate config file in one place (recommended).

1. A separate config file (recommended)

Create the file and load it before the core bundle. Individual pages then need no profanity option at all.

// banned-words.js — banned-word config
window.WebEditorBannedWords = ['stupid', 'idiot'];
<script src="banned-words.js"></script>          <!-- this file first -->
<script src="dist/webeditor.min.js"></script>

2. A data file (URL)

To let an operations team edit the list without changing code, you can point to a file instead. Three formats are accepted: a JSON array, { "words": [...] }, or plain text separated by newlines or commas.

window.WebEditorBannedWords = 'config/banned-words.json';
// or per editor
new WebEditor('#editor', { profanity: { words: 'config/banned-words.txt' } });

In the text format, lines starting with # or // are treated as comments, and surrounding whitespace and duplicates (case-insensitive) are cleaned up automatically. If the file cannot be read, onError('profanity.load') is raised and the editor continues with an empty list.

Reloading the list

The list is read once, on the first check, and cached. Call reloadBannedWords() after changing it at runtime.

window.WebEditorBannedWords = ['new list'];
await editor.reloadBannedWords();   // → the reloaded list

User exceptions — the [Allow] button

When a value that is not really a problem keeps being flagged — a sample number such as 010-1234-5678, or a public contact address — the author can select it in the results dialog and press [Allow]. Allowed values are skipped by both the check and masking.

Because this lets users bypass the check, it is off by default and must be enabled by the developer (in order of precedence): options.profanity.allowButton > window.WebEditorGuardAllow > false.

// banned-words.js — turn it on in the config file
window.WebEditorGuardAllow = true;
// turn it off on one screen
new WebEditor('#editor', { profanity: { allowButton: false } });
APIDescription
allowGuardItems(items)Adds items to the allow list directly ([{ type, value }]) and returns how many were added.
getGuardAllowList()Returns the current allow list.
clearGuardAllowList()Clears the list so everything is checked again.
profanity.onAllow(items)Called right after the user allows an item; you can use it to record the decision on the server.

⚠️ The list lives for this editing session only (in memory) and is cleared when the page is reloaded. For a value that should always be skipped, remove the word from the config file or remove the type from privacy.detect instead. Matching is done on the value, not the type: the personal-data patterns overlap (mobile ⊂ landline ⊂ bank account), so if matching were based on the type, a number allowed as a mobile number could be masked again as a landline.

Matching and masking

  • Matching is case-insensitive — stupid also matches STUPID.
  • Word boundaries are not applied, so partial matches count. That helps in Korean, where particles attach to the word, but short English words can produce false positives (ass inside class). We recommend avoiding very short entries or using a longer form.
  • Masking replaces every character with maskChar (default *) — stupid → ******. Personal data keeps its separators — 010-1234-5678 → ***-****-****.
  • Only text nodes are rewritten, so bold, links and other formatting survive.
  • Dates are not treated as bank accounts — the account pattern used to match YYYY-MM-DD and YY-MM-DD, so even a date inserted from the toolbar (whose default format is YYYY-MM-DD) was reported. Anything outside month 1–12 or day 1–31 is not a date, so 2026-13-45 is still detected, and a four-group value such as 2026-08-03-1 remains an account number.

⚠️ Note: passing an empty array (profanity: { words: [] }) ignores the global setting and disables the check. Saving is not blocked automatically; the calling code is responsible for acting on the validate() result.

setDocumentBackground(opts) / removeDocumentBackground() / getDocumentBackground() → Promise / this / object

Sets or removes the editing area's background image, colour, repeat, and attachment. You can open it from the Document background image toolbar button, or Insert › Document background image… in the menu. The documentBackground option chooses how images are handled (mode: auto / base64 / upload) and preserved (store: auto / wrapper / meta) — the auto default means small (<10KB) files are embedded as base64 and large ones are uploaded. The background also appears in the preview tab and print preview.

await editor.setDocumentBackground({ image: file, color: '#fff7e6', repeat: 'no-repeat', attachment: 'scroll' });
editor.getDocumentBackground();   // { image, color, repeat, attachment, mode, store }
editor.removeDocumentBackground();

⚠️ Note: with store='meta' (the default in upload mode) the background is not part of getHTML(). If you save only the body, as a bulletin board does, store the result of getDocumentBackground() separately and restore it with setDocumentBackground() on load. With store='wrapper' (the base64 default) it is preserved automatically through getHTML() / setHTML().

setUITemplate(name) / getUITemplate() → this / string

Switches the menu UI template at runtime: 'classic' (menu bar + toolbar) ↔ 'ribbon' (tabbed ribbon + large labelled icons + font quick bar). Set the initial value with the uiTemplate option.

editor.setUITemplate('ribbon');
editor.getUITemplate();   // 'ribbon'
setIconTheme(name) / getIconTheme() → this / string

Switches the icon theme at runtime. Use a built-in name — default · gray · blue · colorful · vivid · natural · modern · glass · solid · emoji — or a folder under iconThemePath. Applies to both the classic toolbar and the ribbon tabs and cards.

editor.setIconTheme('vivid');
editor.getIconTheme();   // 'vivid'
toggleToolbar() / toggleMenuBar() → this

Toggles the toolbar and menu bar. Shortcuts: Ctrl+[ (toolbar) and Ctrl+] (menu bar).

editor.toggleToolbar();   // toggle the toolbar (Ctrl+[)
editor.toggleMenuBar();   // toggle the menu bar (Ctrl+])
setTableBorderColor(color) / getTableBorderColor() → this / string

Sets or reads the default border colour for table cells created from now on, and the default in the border colour palette. If not set, it is #000000. The initial value can come from the tableBorderColor option.

editor.setTableBorderColor('#888888');
editor.getTableBorderColor();   // '#888888'
setTableLock(target, mode) / getTableLock(target) → boolean / 'size' | 'readonly' | null

Locks or unlocks a table or cell. In tables with a fixed layout, such as approval forms, cells no longer grow when text is typed into them, and cells that must not change (labels, for example) are protected. The lock is saved in the HTML as a data-we-lock attribute, so writing the attribute into form HTML directly works the same way.

ParameterDescription
targetThe table or cell: an element, APIModel, id, or a selector starting with #, . or [. An element inside a cell resolves to that cell.
mode'size' = lock size and structure (text stays editable) · 'readonly' = lock text editing too · null = unlock
LockWhat it blocks
sizeColumn widths no longer follow the content (long text wraps). Blocks resizing columns, rows and the table; inserting or deleting rows and columns; merging and splitting; deleting the table; adding a row with Tab in the last cell; and growing the table by pasting. Pasting a table fills only the existing cells.
readonlyEverything size blocks, plus editing text and changing background, borders or alignment. On a cell it locks that cell; on a table it locks every cell.
// Example: locking with the API — the column widths you see are fixed at that moment
editor.setTableLock('#form-table', 'size');
editor.setTableLock('label-docno', 'readonly');   // one cell, by id
editor.getTableLock('label-docno');   // 'readonly'
editor.setTableLock('#form-table', null);   // unlock

<!-- Example: writing it into form HTML -->
<table data-we-lock="size">
  <tr><td data-we-lock="readonly">Document no.</td><td></td></tr>
</table>

Use the tableLock option to vary this per screen (full guide in 9-K). The default (null) honours the markers and hides the lock menu. On form-design screens, { menu: true } adds [Table lock] to the right-click menu (lock size · structure, lock all editing, lock / unlock selected cells, unlock). To prevent authors from removing the markers in the HTML tab, pass { allowSourceView: false }. Hovering a locked table shows a 🔒 badge instead of the resize handle (you can turn it off with showIcon: false).

The values 1 and 2 are read as size and readonly, so table-lock values from other editors can be carried over as they are. A lock blocks editing actions on screen; it is not a permission check. We recommend also validating values that must not change on the server.
The UI control methods showMenuBar(bool), enableMenuBar(config?), disableMenuBar(), showStatusBar(bool), setFullscreen(bool), isFullscreen() · toggleFullscreen() (an alias for setFullscreen(!isFullscreen()) that returns the new state), setUI(state), and getUI() are available too.
🖨 Printing and PDF: the print command opens only the print dialog, using an off-screen hidden iframe rather than a separate preview window. saveToPDF() cleans up based on afterprint / matchMedia('print') so the preview does not reappear after you cancel, and it prints just the body even in ribbon mode.

4. Event system

editor.on(eventName, handler)
EventHandler parametersWhen it fires
change(html: string)Fires when the body changes (typing, paste, commands, insertHTML, appendHTML, undo …). setHTML() is a document load and does not fire it; right after loading, the document is treated as unmodified and the undo baseline is reset.
focus()Fires when the editor gains focus.
blur()Fires when the editor loses focus.
tabChange(index: 0|1|2)Fires when the Edit / HTML / Preview tab is switched (sourceview).
selectionchange()Fires when the selection changes.
resize({ width, height })Fires when the editor is resized.
imageInserted({ src, file, node, source })Fires when an image is inserted into the body (attached to the DOM). source indicates how it was inserted (dialog · drop · paste · url) (v2.6.8).
beforeImageAdd({ file, name, size, type, source, preventDefault })Fires right before an image file is inserted. Call preventDefault() to skip it. v2.6.8
imageRejected({ file, name, size, type, source, reason })Fires for each file not inserted because of imageUpload limits or the pre-insert check. reason is 'type' · 'size' · 'count' · 'cancelled'. v2.6.8
beforeVideoAdd({ file, name, size, type, source, preventDefault })Fires right before a video file is uploaded. Call preventDefault() to skip it. source is 'dialog' · 'drop' · 'api'. v2.7.5
videoRejected({ file, name, size, type, source, reason })Fires for each video file not uploaded because it failed the checks. reason is 'type' · 'empty' · 'size' · 'content'. v2.7.5
videoUploadStart({ node, file })Fires after the "Uploading video" placeholder is inserted, right before videoUploadHandler is called. v2.7.5
videoUploaded({ src, file, node })Fires after the upload finishes and the video is in the body. v2.7.5
videoUploadFailed({ file, error })Fires after a failed upload, once the placeholder is removed. onError('videoUploadHandler', err) is called as well. v2.7.5
videoPlayError({ node, src })Fires when the browser cannot play an uploaded video (unsupported codec · bad URL). v2.7.5
fileDropBlocked({ files, blocked })Fires when the dragDrop option blocked a drop. v2.6.8
imageUploaded({ src, file, node })Fires when uploadHandler has finished replacing the base64 data with the server URL (an absolute URL when urlBase is set).
imageUploadStart({ node, file })Fires when an upload starts (v2.6.6.2).
imageUploadFailed({ node, file, error })Fires when an upload fails, after the onUploadFail policy was applied (v2.6.6.2). With keep, the user is also informed that the image remains inside the content (at most once every 5 seconds).
autoSaveReady({ hasDraft, savedAt, backend })Fires once when auto-save has read any remaining draft (right after the editor is created). You can use it to show a "you have a draft" prompt. v2.6.8
storageCleared({ keys, bytes })Fires on every editor when editor data was deleted by WebEditor.clearEditorStorage() or the Browser storage window. bytes is counted in characters.
autoSaveFailed({ error, bytes, key, kept })Fires when auto-save fails because browser storage is full, after clearing its own older copy and retrying. kept indicates whether an older copy is still stored, and bytes is the size it tried to store (UTF-16).
imagesFlushed({ uploaded, failed })Fires when uploadPendingImages() has finished (v2.6.6.2).
imageResized({ file, originalSize, resizedSize, originalWidth, originalHeight, width, height })Fires right after imageResize actually downscales an image (it does not fire if nothing was resized).
zoom({ ratio })Fires when setZoom changes the zoom level.
── UI events ──
fullscreen(on: boolean)Fires when setFullscreen toggles full screen.
uiTemplateChange(name)Fires when setUITemplate switches classic ↔ ribbon.
iconThemeChange(name)Fires when setIconTheme changes the icon theme.
── Multilingual ──
languagechange(lang: string)Fires when setLanguage finishes switching the UI language.
── Checks · forms ──
guard({ ok, blocked, items, counts })Fires when guardBeforeSubmit() detects banned words or personal data. You can use it to show a badge next to the submit button on your page (v2.6.5).
approvalform:change({ fields, changed, errors })Fires in the approvalform add-on after formulas that depend on a changed cell have been recomputed (§9-H, v2.6.6).
── Errors ──
packRestricted({ feature, pack })Fires when an Extension feature is used with a Basic Pack subscription key. feature is the command name (importDocument, wordImport, insertChart, aiOpen …) (6-2-1).
licenseSourced({ from, expiry, pack })Fires when the key handed over by the key auto-sync module licensed the editor. from is 'file' or 'cache' (6-2-2, v2.7.2.0).
error({ context, error })Fires on an internal error, such as a failed upload ('uploadHandler'), a failed import ('docxImport' etc., 9-F), an unreadable banned-word file ('profanity.load') or an unknown language ('setLanguage'). The onError(context, error) option is called at the same time.
For “initialisation finished”, use the onInit(editor) option callback rather than on('ready'). (ready, input, undo, redo and paste are not emitted as events.)
// detect changes
editor.on('change', (html) => {
  console.log('changed:', html.length, 'chars');
});

// detect tab changes
editor.on('tabChange', (index) => {
  const names = ['Edit', 'HTML', 'Preview'];
  console.log('tab switched:', names[index]);
});

// focus handling
editor.on('focus', () => { document.title = 'Editing…'; });
editor.on('blur',  () => { document.title = 'Done'; });

5. Static (global) API

These are called directly on the global WebEditor class.

5-1. Licensing

A licence is applied only through the license initialisation option. Check the result with the onLicenseValid / onLicenseInvalid callbacks (see §6).

new WebEditor('#editor', {
  license: 'WED2-XXXX-XXXX-...',
  onLicenseValid: (info) => { console.log(info); }
});
// Storing in localStorage, a global setLicense API, and applying keys from a popup are not provided.

To have your site server fetch online subscription keys automatically, use the key auto-sync module (6-2-2, v2.7.2.0).

Is the key in place but the editor still in evaluation mode? Please see the Licence key check page (enter the key and site address to get a verdict, with no console needed) or the Licence troubleshooting guide (5 minutes), which offers a one-line console check and goes through the causes one by one.

5-2. Plugin registration

// register a plugin globally — editors that list this name in plugins use it
WebEditor.registerPlugin('myPlugin', MyCustomPlugin);
The import bundles (wordimport-native.min.js and so on) register themselves when they are loaded. You do not need to call registerPlugin(); please just list their names ('wordimport' and so on) in plugins.

5-3. Instance access

// get an instance API model by ID
const model = WebEditor.getAPIModelById('editor-id');

// get one by index (creation order)
const model = WebEditor.getAPIModelByIndex(0);

// list every instance
const models = WebEditor.getAllAPIModels();

// check the version
console.log(WebEditor.version);  // '2.7.4.0'

5-4. Exposed classes

WebEditor.LicenseValidator     // license verification
WebEditor.LicenseManager       // license management
WebEditor.DomainMatcher        // domain matching utility
WebEditor.EvaluationModal      // trial notice modal
WebEditor.LicenseI18n          // localized strings

Static lists and constants (v2.6.8)

NameDescription
WebEditor.READONLY_SAFE_COMMANDSArray of command names that still run in read-only mode (save, print, copy, view toggles, togglePageGuide, togglePageFit, help …). Commands not listed are filtered out in read-only mode by the toolbar, menu bar, ribbon and shortcuts. If you have your own view-only command, please add its name here.
WebEditor.PRESETSOne-line setup definitions ({ full: { plugins, menubar, importMode } }), which hold the values that preset: 'full' uses (1-2).
WebEditor.PRESET_BUILTIN · WebEditor.PRESET_FILESThe built-in plugin list, and a map from optional plugin names to file names in dist/plugins/ (without extension). WebEditor.create loads plugin files from this table.
WebEditor.PRINT · WebEditor.printTextWidthPx()The print paper and margins (A4 · 12mm) and the printable text width (≈703px), which are shared by printing and the A4 print-width guide.

5-5. Browser storage v2.6.8

Overview

Auto-save (autoSave) stores drafts in the browser's localStorage. The quota belongs to the site (origin), about 5MB, not to the editor, so when other pages of the same site use a lot of it, the editor can fill it quickly. This is why some users see "storage is full" while others do not. The editor provides a Browser storage window showing this site's usage and the editor's share, and APIs that delete editor data only.

Entry pointDescription
Auto-save failure noticeThe [View storage] button in the notice. The notice also shows one line with this site's usage.
Menu bar · ribbon"Browser Storage…" in the Tools menu, and [Browser Storage] in the ribbon's Tools group. Shown only on editors with autoSave on, because pages that save posts only to a server database do not use browser storage.
ToolbarThis is not in the default layout. To show a button, add 'showStorageInfo' to the toolbar array.
storageInfo: trueShows the menu and ribbon items even when autoSave is off. This is useful when other pages of the same site use auto-save.
storageInfo: falseHides all of the above. This suits sites that explain storage on their own pages.

API

APIDescription
WebEditor.storageInfo(options?)Returns this site's storage: Promise<{ status, used, limit, limitMeasured, free, editor, other }>. Sizes are counted in characters, the same basis as the browser quota. With { measure: true }, the quota is measured by filling storage temporarily and then removing the data; we recommend doing this only when the user asks.
status'ok' · 'near-full' (90% or more) · 'full' (full, or auto-save failed) · 'blocked' (private window / blocked site data) · 'unavailable'.
editor.itemsEditor data. kind is 'draft' (auto-save) or 'recent' (recent special characters); mine marks keys of editors on this page.
otherThe size and count of data that does not belong to the editor. The editor never deletes it.
WebEditor.clearEditorStorage(options?)Deletes editor data only and returns how many keys were removed. Options are { drafts, recent, keys }; with keys, only the editor keys among them are deleted. Fires storageCleared on every editor. Deletes only the localStorage part; clearEditorStorageAsync() also deletes IndexedDB drafts.
editor.showStorageInfo()Opens the Browser storage window.

Example

// show usage on your own page (e.g. My page)
const info = await WebEditor.storageInfo();
if (info.status === 'full' || info.status === 'near-full') {
  showBanner('Draft storage is running out');
}

// sign-out page — leave no drafts behind on a shared PC
WebEditor.clearEditorStorage({ recent: false });   // drafts only
Shared PCs · one copy per document: we recommend putting the user and document ID in autoSave.scope. The key becomes we-autosave-{scope}, so drafts never mix between users and each document keeps one copy. Please call clearAutoSaved() after a successful submit, and upload images with uploadHandler to keep drafts small.

Choosing where drafts go — autoSave.storage v2.6.8

Auto-save writes to localStorage (about 5MB per site) by default. When posts carry many images, or other pages of the site use a lot of storage, we recommend setting storage: 'indexedDB'. The browser database (IndexedDB) provides hundreds of MB or even GBs depending on free disk space, so "storage is full" practically never occurs.

ValueDescription
'localStorage' (default)Same behaviour as before. getAutoSaved() returns the value immediately.
'indexedDB'Saves to the database dee-editor-drafts. Where the database cannot be opened (under some security settings), it automatically uses localStorage instead. A draft an older version left in localStorage under the same key is moved once and removed.
{ get, set, remove }Storage implemented by the host (a server-side draft, for example). Each function returns a Promise.
APIDescription
editor.getAutoSavedAsync()Returns the exact draft regardless of the storage (Promise<string | null>). Please use this to restore drafts with IndexedDB and host implementations. getAutoSaved() returns the value that was last read in advance.
editor.getAutoSaveBackend()Where auto-save actually writes ('localStorage' · 'indexedDB' · 'custom').
Event autoSaveReadyFires once when any remaining draft has been read. It passes { hasDraft, savedAt, backend }, which you can use for a "you have a draft" prompt.
WebEditor.clearEditorStorageAsync(options?)Works like clearEditorStorage() but also deletes IndexedDB drafts, and returns the exact count (Promise<number>). The synchronous version deletes only the localStorage part.

IndexedDB example

const editor = new WebEditor('#editor', {
  autoSave: { interval: 15000, storage: 'indexedDB', scope: userId + ':' + postId }
});
editor.on('autoSaveReady', async ({ hasDraft }) => {
  if (!hasDraft || !confirm('You have a saved draft. Load it?')) return;
  editor.setHTML(await editor.getAutoSavedAsync());
});

// sign-out — including IndexedDB drafts
await WebEditor.clearEditorStorageAsync({ recent: false });

The Browser storage window counts IndexedDB drafts in "This page's document · Other pages' documents" too, and shows database usage on one line. Because saving is asynchronous, the editor writes once more when the tab is hidden or the page is left (as with localStorage, the last few seconds between intervals may be missed).

6. Licence API

6-1. Applying a licence at initialisation

new WebEditor('#editor', {
  license: 'WED2-XXXX-XXXX-XXXX-XXXX',
  licenseLang: 'ko',

  onLicenseValid: (info) => {
    console.log('license valid:', info.customer, info.expiry);
  },

  onLicenseInvalid: (state) => {
    // state.reason: 'unlicensed' | 'invalid' | 'expired' | 'mismatch'
    console.warn('license error:', state.reason);
  }
});

6-2. Key format

The prefix distinguishes the two generations. Every key issued now is WED2; WED is supported so that keys issued earlier continue to work.

WED2{Base32 payload}{Base32 ECDSA signature}   <- current (v2)
WED {Base32 payload}{8-char HMAC}              <- legacy (v1)

A key is shown in groups of four, as WED2-A3F9-K2M7-…. Hyphens, spaces, line breaks and case are ignored on verification, so it does not matter how it is pasted in. Zero-width spaces, full-width characters and word-processor hyphens that may be picked up in e-mail or documents are also removed.

v2 (current)v1 (legacy)
PrefixWED2WED
SignatureECDSA P-256 with SHA-256First 8 chars of an HMAC-SHA256
What ships in the bundleThe public key only, so a key cannot be forgedThe master secret (same value signs and verifies)
RequiresWeb Crypto (crypto.subtle) on HTTPS or localhost; the built-in pure-JS verifier on plain HTTP, with the same result v2.6.7A build with the master secret set. A build without one (the default bundle) rejects WED keys (reason: 'legacy_disabled') v2.6.5
  • The payload is JSON containing the allowed domains, the expiry as a Unix time (0 = perpetual), the type (perm · year · trial30 · trial180) and the customer id.
  • Key issuance: licence keys are issued by DEXTSOLUTION for your production domains. The private signing key is not included in the distribution.
A non-secure context (plain HTTP) has no crypto.subtle, but from v2.6.7.0 the built-in pure-JS verifier checks a WED2 key's signature exactly as over HTTPS (v2.6.6.x and earlier did not check the signature over http). We recommend using offlineMode or trustedHosts only where key verification must be skipped, such as on an air-gapped network. Please see those two entries in 2. Initialisation options and 6-3.

Why a key is rejected

When a key is rejected, the editor runs in evaluation mode and writes one line to the developer console: [Dee Editor] license key rejected — reason: detail (the key itself is never printed). The same reason arrives as state.info.reason in onLicenseInvalid(state).

ReasonDescription
charsetThe key contains a character that never appears in a key (digits 0 1 8 9, quotes, non-Latin letters). position (counting without spaces and hyphens) and char (U+XXXX) come with it. The key was altered while being passed along; please copy the issued key again as plain text.
signatureEvery character is valid, but the signature does not match. A character may have been replaced in transit, or the key may have been mixed up with another. This is not related to key length or HTTPS.
truncatedThe tail of the key (the signature) is missing. Please allow at least 2,000 characters wherever the key is stored.
format · decodeThe value is not a key, or its content cannot be read.
expiredThe expiry date has passed.
If you ran v2.6.6.x or earlier over http: older bundles did not check the signature over http, so keys with an incorrect signature were accepted there. If a key that worked over http is rejected with signature over https (or on v2.6.7.0 and later), the key was incorrect from the start. Please check it with docs/license-check.html in the package and paste the original key again.
Defect in v2.6.4.0 and earlier: with the secret left empty, the WED signature was still computed, so someone without the secret could forge a legacy key that passed verification. This was fixed in v2.6.5.0. Customers still using WED keys should be re-issued a current WED2 key (ECDSA, public-key verification), which is unaffected.

6-2-1. Subscription packs (Basic · Extension) after v2.7.2.0

Keys issued for the online subscription carry a pack marker, pk. Both packs use the same package; the key decides which features are available. Keys without pk, such as perpetual and annual keys, keep every feature as before.

KeyDescription
pk: 'basic'The editor core and the image editor. Document import (DOCX · XLSX · PPTX · PDF · Markdown · HWP · HWPX), inserting or editing charts and AI writing stop, with a notice bar and the packRestricted event. Saved charts still display.
pk: 'ext'Every feature.
noneNo restriction (perpetual, annual and older keys). The same applies with no key or while the check is still running.

The check sits in toolbar, menu bar and ribbon commands, and at the plugin entry points that drag-and-drop and the public API (importWordFile, chart.insert, ai.run …) all pass through. ai.run rejects with code: 'pack'. Text recognition (OCR) is a separate product and is not tied to the pack.

Checking the pack — example

const editor = new WebEditor('#editor', { license: 'WED2-…', packNotice: false });
editor.licensePack();          // 'basic' | 'ext' | null — once the check has finished
editor.on('packRestricted', (e) => showUpgrade(e.feature));   // to show your own message

6-2-2. Licence key auto-sync (online subscription) after v2.7.2.0

An online subscription issues a new key at every payment. With key auto-sync, your site server fetches the latest key from the store and the editor reads that file and applies the key, so you do not have to change the key in your page code. The existing method (a key written in code) keeps working; this feature runs only when its separate module is loaded.

Components
ComponentDescription
Relay scriptintegrations/license-sync/ in the package. Run one of Node.js 18+ (dee-license-sync.js), Java 8+ (DeeLicenseSync.java) or PHP 7.4+ (dee-license-sync.php) daily on your site server. The store API token stays only in the server environment variable DEE_LICENSE_TOKEN.
Key fileA same-origin JSON file the script saves (default /dee-editor/license.json). It holds only the key, expiry, pack and issue time — never the token.
Editor moduledist/plugins/licensesync.js. Load it after the editor and it registers itself; you do not need to list it in plugins.
Which key is used
  • A key given in code (the license option or WebEditor.defaultLicense) is used while it is valid, and the file is not read.
  • The key file is read only when the code key is missing, expired, for another domain or malformed. The file's key is verified exactly like a code key (signature, expiry, domain).
  • If the file cannot be read, the last received key (browser storage) is used. Several editors on one page share a single request.
When the store is called

The script runs daily but calls the store only from 30 days before the current key expires (for a paid key, your renewal date), every 3 days. On other days it ends without any network access. It calls immediately on first install and with --force. The file is replaced only by a newer key, and the previous file is kept as license.json.bak. On an error the file is left as it is and the script tries again the next day.

Example

# Site server — run daily (cron example). Pass the token only through the environment.
17 3 * * *  set -a; . /etc/dee-license-sync.env; node /opt/dee/dee-license-sync.js --out /var/www/html/dee-editor/license.json

<!-- Page — load the module after the editor -->
<script src="/dee-editor/dist/webeditor.js"></script>
<script src="/dee-editor/dist/plugins/licensesync.js"></script>
<script>
  // Only if the file is not at the default /dee-editor/license.json — same origin only
  WebEditor.LicenseSync.configure({ url: '/editor/license.json' });
  const editor = new WebEditor('#editor');   // a license option may stay
  editor.on('licenseSourced', (e) => console.log(e.from, e.expiry, e.pack));
</script>
APIDescription
WebEditor.LicenseSync.configure({ url, timeout })Sets the key file address (same origin only; another origin is ignored with a warning) and the read timeout (ms, default 3000). Not available in the site config file (code only).
WebEditor.LicenseSync.lastResultThe last read result: { from: 'file' | 'cache' | null, ok, reason }
licenseSourced eventFires when the key from the file (or the stored copy) licensed the editor: { from, expiry, pack }
WebEditor.registerLicenseSource(fn)Registers a key-supplying function directly. fn returns Promise<{ license, from } | null>. It is called only when the code key would leave the editor in evaluation mode, and skipped if it does not answer within 5 seconds. This is the hook the module uses, so you will rarely call it yourself.
Where the site server has no outbound HTTPS to the store, such as closed networks, keep entering the key in code. After moving to a new domain, change the domain in the portal and run the script once with --force. For setup, options and troubleshooting, see integrations/license-sync/README.md in the package.

6-3. Domain matching rules

PatternExample match
example.comexample.com exactly (with or without www.)
*.example.comexample.com itself and every subdomain, such as sub.example.com · a.b.example.com
**.example.comThe same as *.example.com (kept for older keys)
*.example.com allows everything under example.com, not just one level. A look-alike domain such as evil-example.com is not allowed.
Automatically allowed (development): only localhost, loopback (127.x.x.x · ::1) and file://. Private IPs (10.x · 172.16–31.x · 192.168.x) and internal names such as *.local have required a licence key since v2.4. Please include the host in the key, or allow it with trustedHosts while a key is provided.

7. DOM API (WebEditorAPIModel)

7-1. Getting a model

// option 1: from the instance
const model = editor.getAPIModel();

// option 2: by ID
const model = WebEditor.getAPIModelById('my-editor');

// option 3: by index
const model = WebEditor.getAPIModelByIndex(0);

// option 4: the full list
const models = WebEditor.getAllAPIModels();

Reaching a specific element inside the content

The four options above give you the model of an editor instance. For an individual element inside the content, please use the following.

// by ID — searched inside the content only, not the whole document
const cell = editor.getAPIModelById('cell-name');   // null if not found

// by CSS selector — first match / all matches (array)
const one  = editor.querySelector('table.summary td');
const all  = editor.querySelectorAll('p');

// the content root itself (getBody() is a synonym for getRoot())
const root = editor.getRoot();

// batch work — suppress the per-change event and notify once at the end
editor.querySelectorAll('p', { skipRendering: true })
      .forEach(p => p.addClass('para'));
editor.render();                                // → one change event
Without skipRendering, editing 100 elements fires change 100 times, and everything attached to change (autosave, live preview) runs that many times. We recommend running batch work with skipRendering: true and calling render() at the end.

Element-level change detection — watch() v2.6.6

change is a single "the document changed" signal, so it cannot tell you which element changed. Integrations that read and write values in table forms (quotes, applications, approval documents) had to re-read every field on every keystroke, and their own writes came back as change, so they needed a re-entrancy flag. watch() takes a selector and gives you only what changed.

// watch the elements matching a selector — typing, paste, DOM API writes, undo: all of it
const stop = editor.watch('[data-field]', (changed, info) => {
  // changed : the changed elements (APIModel[], deduplicated, document order)
  // info    : { reason: 'input' | 'api' | 'restore', all: boolean }
  //   all:true means the whole body was replaced (undo restore etc.) — every match is passed
}, { debounce: 150 });   // batching delay (ms). Omit to batch one event-loop turn

stop();   // unsubscribe — the last one also disconnects the observer

// a single element — sugar over watch (needs an id)
const off = editor.getAPIModelById('cell-qty').on('change', (m, info) => { … });

// don't listen while I write — this is where you fill computed cells from a change
editor.silently(() => {
  editor.getAPIModelById('cell-sum', { skipRendering: true }).setText(total);
  editor.render();          // the outer change still fires once (autosave must see it)
});
watch and change are separate channels. skipRendering suppresses only change, so changes inside a batch still reach watch. To avoid feedback loops, please run that work inside silently(). During IME composition, changes are held and delivered once when composition ends.

Cloning a tagged element — duplicate() v2.6.6

insertRow() is a helper for growing an empty table and only creates blank cells (<td><br></td>), so it cannot add a form row that has id/data-* tags. duplicate() clones the element as-is next to itself and returns the new model. It works on any element, not only rows.

const rows = editor.querySelectorAll('tr[data-row="items"]');
const n    = rows.length + 1;
const row  = rows[rows.length - 1].duplicate({
  ids:   (old) => old.replace(/^(item-)\d+/, `$1${n}`),  // 'item-1-qty' → 'item-4-qty' · default 'strip' (drop ids) · 'keep'
  empty: '[data-field]',     // clear values only (attributes and contenteditable stay) · true = every leaf
  where: 'after',            // 'before' · 'end' (end of the same parent)
});                              // one change event
ids: 'strip' is the default because duplicate ids are invalid HTML and getAPIModelById returns only the first. Emptied table cells receive &nbsp;, because a truly empty cell collapses and cannot hold the caret.

7-2. Method chaining

Most setter methods return this, so they can be chained.

WebEditor.getAPIModelByIndex(0)
  .setReadOnly(false)
  .setHeight(600)
  .setDefaultFont('Noto Sans KR')
  .setHTML('<p>Initial content</p>')
  .focus();

7-3. Full method list

// content I/O
model.getHTML()               → string
model.setHTML(html)           → this
model.getText()               → string
model.appendHTML(html)        → this
model.insertHTML(html)        → this
model.getSelectedHTML()       → string
model.getSelectedText()       → string
model.clear()                 → this

// state control
model.setReadOnly(bool)       → this
model.isReadOnly()            → boolean
model.isModified()            → boolean
model.resetModified()         → this
model.setHeight(val)          → this
model.getHeight()             → number
model.setWidth(val)           → this
model.getWidth()              → number
model.setTab(index)           → this
model.getActiveTab()          → number
model.showToolbar(bool)       → this

// images
model.insertImage(url)        → this
model.getImages()             → string[]

// content sanitizing
model.clearFormat()           → this
model.clearCSSFormat()        → this
model.removeTag(name)         → this

// runtime settings
model.setDefaultFont(name)    → this
model.setDefaultFontSize(pt)  → this
model.setContentCSS(css)      → this

// events
model.on(event, handler)      → this

// element-level change detection · cloning (v2.6.6) — content element models, not the instance
editor.watch(selector, handler, { debounce })  → stop()      // only what changed
editor.silently(fn)                          → fn's return  // watch does not listen inside
element.on('change', handler)               → off() | null // that element only (needs an id)
element.duplicate({ ids, empty, where })     → APIModel     // clone a tagged element, one change

// lifecycle
model.focus()                 → void
model.destroy()              → void

8. Plugin system

8-1. The plugin interface

class MyPlugin {
  constructor(editor) {
    this.editor = editor;
  }

  /** Called once the editor finishes initializing. Register toolbar buttons, bind events, and so on. */
  init() {}

  /** Handle toolbar and menu commands */
  execute(command, value) {}

  /** Return the active state of toolbar buttons → { [command]: boolean } */
  queryState() { return {}; }

  /** Called when the editor is destroyed. Remove event listeners here. */
  destroy() {}
}

8-2. Global vs per-instance registration

// option 1: register globally — then editors that list the name in the plugins array use it
WebEditor.registerPlugin('myPlugin', MyPlugin);
new WebEditor('#editor', { plugins: ['format', 'table', 'myPlugin'] });

// option 2: register per instance — added to the default built-in list for this editor only
new WebEditor('#editor', {
  plugins: { myPlugin: MyPlugin, video: false }   // false removes it from the default list
});
FormDescription
plugins: ['format', …, 'myPlugin']An array. Only the listed plugins are turned on. Please register your own plugin with registerPlugin() first.
plugins: { myPlugin: MyPlugin }An object. The plugins are added to the default built-in list (or the preset list) for this editor only. A class value is used as is, true turns on an already registered plugin, and false removes it from the default list. Nothing is added to the global registry.

8-3. Using the editor API from a plugin

class MyPlugin {
  init() {
    const html = this.editor.getHTML();
    this.editor.insertHTML('<mark>highlight</mark>');

    // save / restore the selection (around opening a popup)
    this.editor.saveSelection();
    // … show the popup …
    this.editor.restoreSelection();

    this.editor.on('change', (html) => {
      console.log('changed:', html);
    });
  }
}

8-4. Modal focus trap — trapFocus()

An accessibility helper for plugins that open a modal. It keeps focus inside the dialog so Tab cannot escape to the page behind, and returns focus where it came from when the dialog closes (WCAG 2.1 2.4.3 Focus Order and 2.1.2 No Keyboard Trap). Every core dialog uses it.

// when opening — the second argument takes initial focus (defaults to the first focusable)
const trap = editor.trapFocus(modalEl, closeBtn);

// always release on close — otherwise focus stays trapped after the modal is gone
trap.release();
If you build the modal yourself, please add role="dialog", aria-modal="true", an aria-label and Esc to close. trapFocus() only handles focus movement.

8-5. Adding to menus, the ribbon, the context menu and the selection toolbar — plugin extension points (v2.7.1.1)

These APIs let a separate plugin add items to the menu bar, the ribbon, the context menu and the selection toolbar without changing the core. The editor remembers each registration and attaches it again when the menu bar or ribbon is rebuilt (language or UI template switch). Calling again with the same command replaces the earlier registration. setLanguage() initializes plugins again, so registering from init() picks up the new language.

MethodReturnsDescription
editor.addMenuItems(menuKey, items, opts?)thisAdds items to a menu bar menu. menuKey is 'file', 'edit', 'view', 'insert', 'table', 'format', 'tools' or 'help'. With opts.after set to a command name the items go after that item; otherwise they go at the end of the menu, after a separator.
editor.addRibbonCards(tabKey, cards, opts?)thisAdds cards to a ribbon tab. opts is the same as for ribbon.addCards (newGroup, after).
editor.addContextMenuItems(fn, opts?)remove functionAdds items to the end of the context menu, after a separator. They appear in the same place whether the built-in edit menu or the table menu opens. fn(ctx) returns an array of items or null (ctx.kind is 'default' or 'plugin'; ctx.hasTextSel tells whether something is selected). Calling again with the same opts.key replaces the earlier one. To replace the whole menu, use contextMenu.addProvider() as before.
editor.addInlineToolbarButton(def)thisAdds a button to the selection toolbar (inlineToolbar). def is { cmd, title, icon, label, hideAfter }. When inlineToolbar is given as an array, the button shows only if its cmd is in that array.
WebEditor.addIcons(symbols)number addedRegisters <symbol id="…"> icons, used afterwards as '#id' ('id' in the menu bar). Existing ids, including built-in icons, are not overwritten, so name them like icon-<plugin>-….

Give an item action(editor, item, anchor) to call it instead of the command (anchor is the menu position, for opening a popup beside it). Without action, cmd goes to the plugin's execute(cmd). Either way, nothing runs in read-only mode.

Example — using the plugin extension points

class MemoPlugin {
  constructor(editor) { this.editor = editor; }
  init() {
    const E = this.editor;
    WebEditor.addIcons('<symbol id="icon-memo-note" viewBox="0 0 24 24"><path d="M5 4h14v12l-4 4H5z"/></symbol>');
    E.addMenuItems('tools', [{ cmd: 'memoOpen', icon: 'icon-memo-note', label: 'Memo' }]);
    E.addRibbonCards('tools', [{ cmd: 'memoOpen', icon: '#icon-memo-note', label: 'Memo' }], { newGroup: true });
    E.addContextMenuItems((ctx) => ctx.hasTextSel
      ? [{ label: 'Memo on selection', icon: '#icon-memo-note', action: () => this.open() }]
      : null, { key: 'memo' });
    E.addInlineToolbarButton({ cmd: 'memoOpen', icon: '#icon-memo-note', title: 'Memo', hideAfter: true });
  }
  execute(cmd) { if (cmd === 'memoOpen') this.open(); }
  open() { /* open a panel */ }
}
WebEditor.registerPlugin('memo', MemoPlugin);
If you build the menu bar from your own array, give each menu object a key so addMenuItems can find it. Your array itself is not changed.

9. MS Word import API

Make sure dist/plugins/wordimport-native.js is loaded.

9-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/wordimport-native.min.js"></script>
const editor = new WebEditor('#editor');

document.getElementById('import-btn').addEventListener('click', () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.docx';
  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (file) await editor.importWordFile(file);
  };
  input.click();
});

9-2. Drag and drop

const dropZone = document.getElementById('drop-zone');

dropZone.addEventListener('dragover', (e) => {
  e.preventDefault();
  dropZone.classList.add('drag-over');
});

dropZone.addEventListener('drop', async (e) => {
  e.preventDefault();
  dropZone.classList.remove('drag-over');
  const file = e.dataTransfer.files[0];
  if (file && file.name.endsWith('.docx')) {
    await editor.importWordFile(file);
  }
});

9-3. Engine registration — WordImportEngineRegistry (advanced)

Word import engines are listed in the global WordImportEngineRegistry (it exists once wordimport-native.js is loaded; the default engine 'native' is registered when the plugin is first turned on). An engine is a class with its name and priority as static members; you pass that single class to register(EngineClass).

const R = WordImportEngineRegistry;
const engines = R.all();               // available engines, by priority
const engine  = R.best();              // the first of them
const native  = R.byName('native');

class MyEngine {
  static name = 'custom';
  static displayName = 'In-house converter';
  static priority = 30;                 // higher goes first
  static isAvailable() { return true; }
  static async convert(arrayBuffer, options) { return { html: '…', warnings: [] }; }
}
R.register(MyEngine);

9-4. Supported conversions

OOXMLHTMLNotes
<w:p><p>Maps to a plain paragraph.
<w:p> + heading style<h1>–<h6>
<w:b><strong>
<w:i><em>
<w:u><u>
<w:color>color: #RRGGBB
<w:highlight>background-color
<w:tbl> + <w:tblGrid><table> + <colgroup>Column widths are preserved exactly.
<w:shd>background-colorMaps to the cell background.
<w:tcBorders>border-colorMaps to the cell border colour.
<a:blip><img src="data:...">The image is inlined as base64.
<wp:extent>width / heightMaps to the displayed size (EMU → px).
<w:hyperlink><a href="...">
Word files converted from PDF: a PDF turned into Word has no Word tables (<w:tbl>); the table lines are images placed behind the page, and the cell text is in positioned text frames (<w:framePr>). When most body paragraphs are such frames, import reads the lines from those pictures and rebuilds tables, bordered boxes, merged cells and shading; pictures such as seals are cut out and kept. Letter spacing and side-by-side boxes follow the original layout. Tables aligned only by spacing, without lines, are not turned into tables. v2.6.8

9-A. Hangul HWPX import API improved in

Requires loading dist/plugins/hwpximport-native.min.js and adding 'hwpximport' to plugins (opt-in). This plugin reads only Hangul's standard XML format .hwpx (OWPML). Binary .hwp files are imported by the separate hwpimport plugin; please see 9-I v2.6.7.0.

9-A-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/hwpximport-native.min.js"></script>
const editor = new WebEditor('#editor', {
  plugins: ['format', 'table', 'link', 'hwpximport']
});

document.getElementById('import-btn').addEventListener('click', () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.hwpx';
  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (file) await editor.importHwpxFile(file, { mode: 'replace', maxTableWidth: 740 });
  };
  input.click();
});

9-A-2. Drag and drop

const dropZone = document.getElementById('drop-zone');

dropZone.addEventListener('drop', async (e) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0];
  if (file && file.name.endsWith('.hwpx')) {
    await editor.importHwpxFile(file);
  }
});

9-A-3. importHwpxFile options

OptionTypeDefaultDescription
mode'cursor' | 'append' | 'replace''cursor'Specifies where to insert. 'replace' replaces the whole body.
maxTableWidthnumber—Tables wider than this pixel width are scaled down proportionally (narrower tables keep their original width).
silentbooleanfalseWhen set to true, the content is inserted immediately with no conversion dialog.
showLogbooleanfalseIndicates whether conversion warnings and statistics are shown.
We recommend a maxTableWidth that matches the editor body width, 740–780px. The demo page (demo/hwpximport.html) uses 740px.

9-A-4. Supported conversions (OWPML → HTML)

OWPMLHTMLNotes
<hp:p><p>Maps to a paragraph, with alignment (text-align) applied.
<hh:bold/><strong>Bold is determined by the presence of charPr.
<hh:italic/><em>
underline (type≠NONE)<u>
charPr textColor / heightcolor / font-sizeThe height value equals pt×100.
<hp:tbl> + cellSz<table> + cell width / heightConverts HWPUNIT to px (÷75).
cellSpan colSpan / rowSpancolspan / rowspanMaps to merged cells.
borderFill · winBrush@faceColorborder / background-colorMaps to borders and solid cell shading.
borderFill · hc:gradationbackground-image: linear/radial-gradientMaps to gradient cell backgrounds.
paraPr · lineSpacing (PERCENT / FIXED)line-heightMaps to paragraph line spacing, including nested hp:switch/default.
subList@vertAlignvertical-alignMaps to vertical cell alignment.
<hp:pic> (BinData)<img src="data:…">Images are inlined as base64 and displayed at hp:sz. Floating pictures that overlap text (logos, stamps) are height-capped; "top and bottom" (TOP_AND_BOTTOM) pictures keep their original size in their own block. With an uploadHandler, BMP pictures are converted to PNG before upload (so the post saves even if the upload server rejects BMP).
<hp:caption> (table, picture)<p> before/after the objectA caption on the top side (TOP) goes before the object; any other side goes after it.
Table column boundaries, table border<colgroup>, borderColumn widths are solved from every cell's width. Missing edge-cell lines are filled with the table's own border, except on tables where more than half of the edge sides have no line (layout tables such as org charts).
hh:slash, hh:backSlash (cell diagonals)background-image: linear-gradientCell diagonals (/, \) are drawn as cell background lines.
Font names (HY헤드라인M, etc.)font-family aliasHY fonts that Chrome and Edge cannot find by their Korean name (HY헤드라인M, HY중고딕, …) also get the browser-side name (HYHeadLine, …). HWP import does the same. HY fonts draw the no-break space (U+00A0) as a box, so alignment spaces in those fonts are written as U+2004.
Vector shapes polygon / rect / ellipse / curveInline <svg>Preserves drawing objects without text (default grey fill)
Symbol-font characters (PUA, U+E000–F8FF)Standard UnicodeReplaces glyphs that would otherwise render blank (e.g. ·)
<hp:tab leader>Dotted / dashed leader (border-bottom)Preserves the “Title … page” dots in a table of contents.
hp:p@pageBreak · a standalone 목차 / 차례 heading (Korean for “contents”).we-page-breakInserts a page break when printing (separates cover from contents).
Text inside <hp:drawText>Paragraph textExtracts text from rectangles, containers, and other shapes.

9-A-5. Limitations

  • Supported (added in v2.6.7.0): equations (same renderer as HWP import — fractions, scripts, radicals, brackets, matrices, ladders, long division), automatic numbering of numbered paragraphs (question numbers), footnotes / endnotes (markers in the document’s number style, footnote bodies at the end of their page, endnotes at the end of the document), the table’s own border, multi-column layout (a table per page with one cell per column), text shadow, image cell fills.
  • Unsupported: precise layout of SmartArt and complex drawing groups, headers / footers, text wrapping (flow around shapes), and shape rotation.
  • Bulleted and numbered lists and hyperlinks are preserved as text (the list and link structure is not reproduced).
  • Vector shapes are approximated from their vertices, and shapes without a fill or stroke are drawn in default grey so they remain visible (colours may differ from the original). Curves (curve) connect vertices without control points.
  • This plugin accepts the .hwpx / OWPML standard only. Binary .hwp files are handled by the hwpimport plugin (9-I), and the unified "Import document" button routes files by extension. Unsupported elements keep their text and raise a warning.
For engine internals, see the developer document docs/04_API-development/HWPX_IMPORT.md (architecture, limits, coordinate conversion).

9-B. Markdown viewer / editing API

Requires loading dist/plugins/markdown-native.min.js and adding 'markdown' to plugins (opt-in). It converts using GFM (GitHub Flavored Markdown) and provides import, export (round-trip), and safe rendering.

9-B-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/markdown-native.min.js"></script>
const editor = new WebEditor('#editor', {
  plugins: ['format', 'image', 'table', 'link', 'markdown']
});

9-B-2. Public API

MethodReturnsDescription
editor.importMarkdownFile(file, options?)void (async)Converts a .md file and inserts it into the body.
editor.setMarkdown(md, options?){html, warnings}Sets the body from a Markdown string.
editor.getMarkdown(options?)stringSerialises the current body (HTML) back to Markdown (round-trip).
editor.viewMarkdown(md, options?){html, warnings}Converts Markdown to a sanitised HTML string for rendering, without inserting it.

9-B-3. Examples

// Markdown → body
editor.setMarkdown('# Title\n\n**bold** and [a link](https://example.com)\n\n- item');
editor.setMarkdown(mdText, { mode: 'append', baseUrl: '/docs/' });

// body → Markdown (round-trip)
const md = editor.getMarkdown();

// render sanitized HTML only, without inserting (for viewers)
const { html, warnings } = editor.viewMarkdown(mdText);
previewEl.innerHTML = html;

// import a .md file
input.onchange = (e) => editor.importMarkdownFile(e.target.files[0], { mode: 'cursor' });
A Markdown import button is added to the toolbar, and you can also drag and drop .md (or .markdown) files onto the editing area.

9-B-4. Options

OptionTypeDefaultDescription
mode'cursor' | 'append' | 'replace''replace'Specifies where to insert (on import or set).
baseUrlstring''Specifies the base URL for relative links and image paths.

9-B-5. Supported syntax (GFM)

MarkdownHTML
# ~ ######<h1>~<h6>
**bold** · *italic* · ~~strikethrough~~<strong> · <em> · <del>
`inline code` · ```fenced```<code> · <pre><code>
[text](url) · ![alt](src)<a> · <img>
- / * / 1. lists · - [x] checkboxes<ul> / <ol> / <li> · checkboxes
GFM tables (| … |, :--: alignment)<table>
> quote · --- divider<blockquote> · <hr>

9-B-6. Security

Every conversion follows an escape-first policy: injected <script> and javascript: / data:text/html links are blocked automatically. This applies equally to viewMarkdown() and setMarkdown().

9-B-7. Standalone viewer demos

There are widget demos that render Markdown without an editor: demo/markdown.html (edit ↔ full-view tabs, sizing API) and demo/markdown-editor.html (round-trip inside the editor). For details, see docs/04_API-development/MARKDOWN_PACK_API.md.

9-C. Excel XLSX import API

Converts Excel .xlsx (SpreadsheetML) into HTML tables in the browser, without any external libraries or servers (the shared WebZipReader plus DOMParser). It is opt-in: load the xlsximport-native.min.js bundle and add plugins:['xlsximport'].

9-C-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/xlsximport-native.min.js"></script>
const editor = new WebEditor('#editor', { plugins: ['format', 'table', 'xlsximport'] });
await editor.importXlsxFile(file, { mode: 'replace', allSheets: true });
You can import from File menu → Import Excel (XLSX)…, the Excel toolbar icon, by dragging in a .xlsx file, or through the API. To call the engine directly, use XlsxEngine.convert(arrayBuffer, opts), which returns { html, warnings, sheets }.

9-C-2. importXlsxFile options

OptionDefaultDescription
mode'cursor'Specifies the insertion mode: 'cursor' / 'append' / 'replace'.
silentfalseIndicates whether the file is converted immediately with no dialog.
maxTableWidth—Specifies the maximum table width per sheet (px).
allSheetstrueIndicates whether every (non-hidden) sheet is imported. false imports only the active sheet.
sheets—Specifies an array of sheet names (overrides allSheets).
sheetSeparator'heading'Specifies the sheet separator: 'heading'/'pagebreak'/'hr'.
includeHiddenfalseIndicates whether hidden sheets are included.

9-C-3. Supported and unsupported

SupportedUnsupported
Sheet → table conversion · grid repair for empty cells and rows · merged cells (colspan / rowspan) · bold, font colour, solid backgrounds · per-side borders · fonts (family, size, bold, italic, underline), number formats (date, currency, percentage, thousands, decimal places) · text overflow absorbing empty cells and wrapping when it still does not fit · column widths and row heights · multiple sheets (stacked, with sheet tabs) · form-control check boxes and option buttons (☑/☐ · ◉/○ with their labels, checked state kept) · =TODAY()/=NOW() recalculated to today (and the day offsets built on them, such as =date+30) Charts, pivots, sparklines · conditional formatting and data validation · images and shapes inside cells · theme colours (@theme) · formula recalculation (cached results are shown — =TODAY()/=NOW() and day offsets built on them are the one exception) · other form controls (list boxes, buttons) · very large sheets are capped by maxCells

What the import tells you afterwards — conversion warnings v2.6.5.1 · v2.6.6

Because these change or blank out values, they are never applied silently: each one leaves one warning line (showLog, or warnings from XlsxEngine.convert()).

Warning keyWhenBehaviour
imp.errorCellsHiddenCells holding an error value — #REF!, #N/A, #DIV/0!Such cells are imported as empty cells; they are left over from a broken formula and are not real content. A literal #REF! pasted as text is a string and is kept.
imp.narrowNumsHiddenNumbers that do not fit their column (estimated from font size × digit count)Excel masks such cells with #, so the value is left blank. The estimate is deliberately conservative, so a number that Excel shows is never hidden.
imp.xlsxVolatileRecalc=TODAY() / =NOW() and day offsets built on them (=date+30)The formula is recalculated to today instead of the value saved in the file. Every other formula keeps its cached result.
Overflow rules: text flows into empty cells to the right; numbers never cross a cell boundary (as in Excel). An empty neighbour is absorbed with colspan only when its top and bottom borders match the absorbing cell; otherwise, an underline would stretch to the end of the table. When borders differ, the cell stays as it is and only the text overflows (white-space:nowrap; overflow:visible): the neighbour's borders stay in place and the text passes over them. This applies only when the text fits in the free space; otherwise it wraps inside its own cell.
For details (conversion rules, coordinates, pitfalls) see docs/04_API-development/XLSX_IMPORT.md.

9-D. PowerPoint PPTX import API

Renders PowerPoint .pptx (PresentationML) as absolutely positioned HTML per slide using an in-house engine without any external libraries. It is opt-in: load the pptimport-native.min.js bundle and add plugins:['pptimport']. The original layout (horizontal position and alignment) is preserved, and slides are scaled to 960px wide by default.

9-D-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/pptimport-native.min.js"></script>
const editor = new WebEditor('#editor', { plugins: ['format', 'image', 'table', 'pptimport'] });
await editor.importPptxFile(file, { allSlides: true });   // or slides:[1,3,5]
You can import from File menu → Import PowerPoint (PPTX)…, the PPT toolbar icon, by dragging in a .pptx file, or through the API. In the preview (doc-preview.html), you can browse slides using tabs.
🆕 Selecting a slide range — enter something like 2-8, 11, 12 in “Slides to import” in the dialog, and only those slides are imported (the total is shown; leave it blank to import all). Reversed ranges (8-2), duplicates, and full-width punctuation are accepted, and out-of-range numbers are trimmed to the valid range. The API equivalent is slides:[2,3,4].

9-D-2. importPptxFile options

OptionDefaultDescription
modereplace / cursorSpecifies the insertion mode: 'cursor' / 'append' / 'replace' (replace when not silent, cursor when silent).
silentfalseIndicates whether the file is converted immediately with no dialog.
showLogfalseIndicates whether conversion warnings are shown.
slides—Specifies an array of slide numbers to import (1-based). When unset, all slides are imported.
allSlidestrueIndicates whether all slides are imported.

9-D-3. Supported and unsupported

SupportedUnsupported
Absolute slide positioning (layout preserved) · vector shapes (prstGeom / custGeom → SVG) · fills and outlines with theme references · theme colours (schemeClr + lumMod / shade / alpha) · tables (merges, row heights, cell borders) · charts (pie / doughnut / bar / line as SVG) · images (srcRect cropping, EMF approximation) · inherited placeholder colours and sizes · text insets, alignment, and spAutoFit WMF · EMF gradients, text, and clipping · pattern fills · radial gradients (approximated as linear) · fixed line spacing in points · animations, transitions, and notes · SmartArt without a drawing part (placeholder shown) · PPTX export
If EMF pictures must be shown exactly, we recommend converting them to PNG in PowerPoint before importing. For details, see docs/04_API-development/PPTX_IMPORT.md.

9-E. Shape insertion included in the core

Inserts editable vector shapes and text boxes into the body. This is part of the core, not a separate bundle. Shape state (type, position, size, colour, text) lives only in the body DOM as inline styles and data-* attributes (self-serialising), so position and form survive getHTML(), undo, reloading, and read-only rendering elsewhere.

// part of the core — just having 'shape' in plugins shows the 'Insert shape' toolbar button
const editor = new WebEditor('#editor', { plugins: ['format', 'table', 'shape'] });

// The shape palette opens from the toolbar [Insert shape] button, Insert menu [Shape] or the ribbon Insert tab (cancel with ✕, Esc or clicking outside). There is no public method that opens it from code.
  • Available shapes: 7 lines / connectors · 26 basic shapes (rectangle, rounded rectangle, polygons, ellipse, pie, doughnut, heart, lightning, moon, cylinder, cube, and more) · 9 block arrows · text box.
  • Structure: each shape sits as .we-shape[data-shape][data-sid] inside .we-shape-layer at the top of the body (an absolutely positioned anchor that takes up no space in the text flow).
If you pass an explicit toolbar array, please add 'insertShape' to groups.media (or the toolbar array) so that the button appears. Without the shape plugin, the [Shape] card on the ribbon's Insert tab is hidden as well. Rotation, flipping, automatic connector anchoring, and group alignment are not yet supported (shapes are axis-aligned and solid-filled). For details, see docs/04_API-development/SHAPES.md.

9-F. Import failures & drop guidance

When someone drops an unsupported format or a damaged document onto the body, guidance explaining the cause and what to do appears automatically. No configuration is required. A file chosen in the file picker or passed to importDocumentFile() is reported with the same warning notice (a blocking alert is not used).

SituationWhat the notice says
Dropping an unsupported format The notice shows the file name plus format-specific advice (.hwp → .hwpx, .doc → .docx, .xls → .xlsx, .ppt → .pptx, plus notes for PDF, archives, text, and HTML) and the formats you can currently drop.
A damaged, mismatched, or password-protected document The notice shows the cause (“the file is damaged or its format is wrong”, and so on) plus what to do. The technical detail (the engine's own error) is shown as well.
The formats you can drop are determined by the plugins actually loaded. If you never loaded the xlsximport bundle, for example, dropping an .xlsx file reports “this format cannot be imported”.

Import failures are also delivered through the error event, which you can use for server-side logging.

editor.on('error', ({ context, error }) => {
  // example contexts: 'docxImport' · 'hwpImport' · 'hwpxImport' · 'xlsxImport' · 'pptxImport' · 'pdfImport' · 'uploadHandler'
  reportToServer(context, error.message);
});
The notice appears as a toast at the bottom of the screen with role="alert" and aria-live, so screen readers announce it too. It disappears on its own and also has a close button.

9-G. Image editing (DEXT Image 2.2) built in

Select an image in the content and edit it — crop, resize, rotate (90º and free-angle) and flip, mosaic, fill, text, shapes and arrows, drawing, colour adjustment, filters, frames — and the result is placed back in its place. Built in since v2.6.5, so the host page has nothing to set up. Once you create an editor, [Edit image] appears in three places, and double-clicking an image opens it as well.

PlaceNotes
Double-click the image v2.6.6.1When you double-click an image in the content, the editor opens on that image. The first click preloads the editor, so the second click opens it at once. It is not available in read-only mode or for images inside slides (PPTX) or shapes. You can turn it off with imageEditor: { dblclick: false }.
ToolbarThe button sits right next to [Insert image]. The command name is imageEdit; you can use it in custom toolbar arrays and on the UI settings page.
Menu barAppears under Insert › Edit Image… (the Insert card in the ribbon UI).
Menu under the imageAppears next to caption, link and alternative text when an image is selected, and opens that image. v2.6.6.1 While the editor window is open, that image's menu is locked (buttons disabled, "Editing in DEXT Image…") so that the result is applied to an unchanged image. It unlocks as soon as the window closes (Apply, Cancel or ✕), and pressing Edit again brings the existing window forward instead of opening a second one. If you need to check this state, call the image plugin's isImageEditing(img).
The bundled version is DEXT Image 2.2 v2.6.7.0. The distribution's dext-image/ folder contains the whole product, version 2.2.0 (editor bundle, Konva, add-ons, icon themes, language packs, configuration file). Every 2.2 feature is available without a separate key — the basic tools (crop, resize, rotate / flip, mosaic, colour fill) and the 2.2 tools (text, shapes / arrows, drawing, brush mosaic, colour adjustment, filters, free-angle rotation, frames) open on any domain (see 9-G-6). There is nothing to download separately and no script to add to the page. This version also supports opening and saving WebP (see 9-G-4-1).
It is not built into the core bundle. The editor (a single-file bundle, dext-image.bundle.min.js, 184 KB, plus Konva) lives in the distribution's dext-image/ folder and is loaded the first time the button is pressed. A page that never edits an image downloads no extra bytes, and the core stays dependency-free. v2.6.5.1 Previously, some forty source modules were fetched one by one (about 130 requests). With the bundle, the first load takes 6 requests (probe · config · Konva · CSS · bundle) and the pop-up window needs 3. The loader and the pop-up try the bundle first and fall back to the sources (src/index.js). Add-ons, language packs and HEIC are still fetched on demand.

9-G-1. Layout and path

We recommend leaving the distribution as it was unpacked. With dist/ and dext-image/ side by side the editor finds it on its own.

your-site/
├── dist/webeditor.min.js        ← starting here…
└── dext-image/                  ← …it looks for ../dext-image/ (then ../dext-image-2.0.0/)
    ├── src/  vendor/  addons/
    └── dext-image.config.js

If you keep it elsewhere, please specify the location. Make sure the path ends with /.

// per instance
new WebEditor('#editor', { imageEditor: { path: '/static/dext-image/' } });

// or once for the whole page
WebEditor.imageEditorPath = '/static/dext-image/';
A web server is required. The editor ships as ES modules, so it cannot be loaded on a page opened from file://. On such a page the [Edit image] button is dimmed and its tooltip gives the reason. Pressing it shows the notice "The image editor could not be loaded" once (repeated presses do not stack notices). The background preload when an image is selected or the button is hovered stays silent if it fails. Nothing else in the editor is affected.

9-G-2. The imageEditor option

The default (omitted) is enough. You only need this option to turn the feature off or to change how it opens.

ValueBehaviour
falseNo button or menu entry is shown, and the editor is never loaded.
pathSpecifies the location of dext-image/ (with a trailing /). It is auto-detected when omitted.
modeSpecifies the display mode. 'popup' (default) shows a separate window, and 'inline' shows the editor inside target.
targetSpecifies where the inline editor renders (selector or element). It is required in inline mode.
actionBarfalse removes the entry from the menu under the image only (the toolbar button remains).
editorOptionsSpecifies the DextImage options, such as language, popupWidth, popupHeight, …. Without language, it follows the editor's language. The bundled version opens every 2.2 tool without a key, so you do not need to set license (it is not read even if you do).
onNoTargetCalled when there is no image to edit. By default, the editor shows the notice "Click an image to select it first."
onPopupBlockedCalled when the browser blocks the window. By default, an editor notice is shown.
onNoUploadHandlerCalled when there is no uploadHandler, so the result is embedded as base64.
onApplyErrorCalled when the edit result could not be applied to the content.
// ① Default — write nothing. All three buttons appear; the editor opens in a new window.
new WebEditor('#editor', { uploadHandler });

// ② Off
new WebEditor('#editor', { imageEditor: false });

// ③ Open below the content; toolbar button only
new WebEditor('#editor', {
  imageEditor: { mode: 'inline', target: '#image-editor', actionBar: false,
                 editorOptions: { popupWidth: 1280, popupHeight: 900 } },
});

9-G-3. Display mode and icon

modeBehaviour
'popup' (default)Opens in a separate window. It does not cover the content, so you can compare against the original, and the tools are not cut off on a narrow screen. The window closes automatically once you save.
'inline'Opens inside the element that target points to.
Blocked pop-ups: if the browser blocks the window, an editor notice asks you to allow pop-ups for the site and try again (override with onPopupBlocked). The window is opened directly from a button click, so ordinary settings do not block it. v2.6.5.1 The editor is fetched ahead of the click — when an image is selected, and when the [Edit image] button is hovered or focused. Previously it started loading only on the first click, and on a slow connection the user-gesture window expired before loading finished, so only the first attempt was blocked. Pages that never edit still download nothing.

The icon is the core sprite's #icon-image-edit (a photo frame with a pencil), drawn so it does not look like the button that inserts an image. All eight bundled icon themes (assets/icon-themes/) include an icon-image-edit.svg in their own style, so the button is still shown when iconTheme is set. If you maintain your own theme folder, add a file of the same name there.

9-G-4. Where the result is saved

The edited image goes through the editor's own uploadHandler, so upload policy and auth headers stay in one place.

SituationBehaviour
uploadHandler setThe result is converted into a File object and passed to the handler, and the returned URL replaces the image in the content.
No uploadHandlerThe result is inserted as base64, the same as the editor's default.
Automatic downscaling before upload (imageResize) applies to the insertion path only. An edited result does not go through it and is not shrunk. This is intentional, so that something the user just edited on purpose is not reduced again.

9-G-4-1. Save format and WebP v2.6.7.0

The editor opens PNG · JPEG · GIF · BMP · WebP and saves the result as PNG · JPEG · WebP. The default outputFormat:'auto' saves a JPEG (or HEIC) original as JPEG and anything else (PNG, GIF, BMP, WebP) as PNG, so transparency is never lost. To get the edited result as WebP, set outputFormat:'webp' (for photographs it is far smaller than PNG).

Option (imageEditor.editorOptions)DefaultDescription
outputFormat'auto'Specifies the output format: 'auto' · 'png' · 'jpeg' · 'webp'. 'auto' uses JPEG for JPEG / HEIC originals and PNG for everything else.
outputQuality0.92Specifies the JPEG / WebP quality (0–1).
outputBackgroundColor'#FFFFFF'Specifies the colour that fills transparent areas when saving as JPEG.
addonPathnullSpecifies the location of the WebP encoder / HEIC decoder add-ons. It should be left unset when the distribution is used as shipped.
// always save the edited result as WebP (to keep files small)
new WebEditor('#editor', {
  imageEditor: { editorOptions: { outputFormat: 'webp', outputQuality: 0.9 } }
});
WebP saving works in Safari too. Where the browser cannot encode WebP from a canvas, the libwebp (WASM) encoder in the distribution's dext-image/addons/webp/ takes over; it is fetched only when needed. Without the add-on folder, the result is saved as PNG instead without an error (the file is simply larger). If the server-side allow-list (wherever uploadHandler uploads to) does not include image/webp, the edited result is rejected on upload, just as when a WebP file is inserted into the content (3-3).

9-G-5. Which image gets edited

HEIC photos (from an iPhone) open too, as long as the browser can decode them (Safari does natively). If it cannot, a notice tells you so.

The image to edit is the one you click in the content. Images inside a caption (figure) or with a hyperlink are recognised too, and if the content contains exactly one image, it is used without a click. If there is no target, the editor does not open and a notice is shown instead. A remembered image that has since left the content (setHTML() and the like) is discarded, so a detached node is never opened.

When opened from the menu under an image, that image is the target. It does not fall back to click tracking, so a selection change in between cannot send the wrong image to the editor.

9-G-6. Editions

The DEXT Image that ships with Dee Editor is the 2.2 edition. No key and no setting are needed, and every tool opens on your production domain as well.

GroupTools
Basic tools Open, crop, resize, canvas, 90º rotate and flip, mosaic, fill, undo, zoom, export
2.2 tools Text, shapes and arrows, drawing and eraser, brush mosaic, colour adjust, filters, free-angle rotation, frames
The badge at the bottom of the editor reads 2.2. The license values in dext-image.config.js are not read, so you can leave them empty. If tools show a padlock, an old dext-image/ folder or a browser cache is still being used. Please replace it with the distribution's dext-image/ and hard-refresh (Ctrl+F5).

9-G-7. Appearance — skins and icon themes

The editor toolbar's button icons and colours can be changed. It defaults to icon-only buttons with the solid theme, so there is nothing to set. Pass options through imageEditor.editorOptions only if you want to change that.

new WebEditor('#editor', {
  imageEditor: { editorOptions: {
    skin: 'default',          // colour skin
    iconTheme: 'solid',       // the default; 'default' is the built-in set (no requests)
    toolbarLabels: 'icon',    // the default; 'text' · 'both'
  } },
});
The distribution ships the solid theme under dext-image/icon-themes/, and the folder is located relative to the product, so iconThemePath does not need to be set (it is needed only when the theme folder is outside the product, as an absolute path). If you add a folder next to it containing SVGs with the same names, you can use it by that name. This is separate from the editor's own iconTheme, so please set both if you want them to match.

9-G-8. Language

The editor follows the host editor's language, so there is nothing to do. After setLanguage() the plugin is rebuilt in the new language, so the next open uses it. To fix the language regardless, pass editorOptions.language (built-in: ko and en).

9-G-9. Pages wired the old way

Up to v2.6.4, the add-on was registered manually with WebEditor.registerPlugin('dextImage', createDextImagePlugin()) plus 'dextImage' in plugins. That code keeps working. When plugins contains 'dextImage', the core adds no button of its own, so you never get two buttons. New pages do not need any of this.

A working example is demo/image-edit.html.

9-G-10. Batch-resizing images already in the content — the image-processing API v2.6.6

The imageResize option (§2-1-8) only applies when an image is inserted. To shrink images that are already in the body — a saved post reopened for editing, large pictures brought in from Word or Hangul, images inside pasted HTML — use DEXT Image's image-processing API. No editor window opens; three functions handle loading, shrinking and encoding.

FunctionWhat it doesReturns
WebEditor.loadImageEditor(path?)Loads the DEXT Image module (cached). It is the same loader the editor window uses, so it finds dext-image/ next to dist/ on its own and prefers the bundle when present.Promise<{ loadUrl, loadFile, Pipeline, encode, … }>
loadUrl(src, { maxImageWidth, maxImageHeight })Puts the image on a canvas, applying the EXIF orientation. data: URLs work too.{ canvas, originalWidth, originalHeight, tainted, format }
new Pipeline(canvas).render(ops)Applies edit operations. Resizing is { t: 'resize', w, h }; reductions below 1/2 are done in steps to avoid aliasing.HTMLCanvasElement
encode(canvas, { format, quality })Encodes as 'jpeg' · 'png' · 'webp'. Browsers that cannot encode WebP (Safari) fall back to PNG or JPEG depending on transparency and report fallback:true.{ blob, format, fallback }
const dxi  = await WebEditor.loadImageEditor();
const imgs = editor.querySelectorAll('img', { skipRendering: true });   // batch the writes, render() once at the end

for (const m of imgs) {
  const src    = m.getAttribute('src');
  const loaded = await dxi.loadUrl(src);
  if (loaded.tainted) continue;                          // cross-origin without CORS → the canvas cannot be read

  const { width: w, height: h } = loaded.canvas;
  const s = Math.min(1, 1200 / w, 1200 / h);              // keep the ratio · never upscale
  if (s >= 1) continue;                                   // already within the cap

  const canvas   = new dxi.Pipeline(loaded.canvas).render([{ t: 'resize', w: Math.round(w * s), h: Math.round(h * s) }]);
  const { blob } = await dxi.encode(canvas, { format: 'jpeg', quality: 0.85 });

  const file   = new File([blob], 'image.jpg', { type: blob.type });
  const newSrc = editor.options.uploadHandler
    ? await editor.options.uploadHandler(file)            // upload, get a URL
    : await toDataURL(blob);                               // otherwise base64 — a helper that turns FileReader.readAsDataURL into a function returning a Promise
  m.setAttribute('src', newSrc);
}
editor.render();                                             // one change event
Shrink only, keep the display size: images within the cap are skipped and the width attribute is left alone, so the layout does not move. Format: we recommend following the original MIME type, because a PNG converted to JPEG has its transparency replaced with white. If re-encoding makes a file larger (photographic PNGs), keep the original. Skip SVG (vector), animated GIF (only the first frame would remain) and cross-origin images (tainted:true; they need CORS headers from the image server).

render(ops) accepts more than a resize. The basic operations are listed below; several can be passed in one array and are applied in order.

tParametersDescription
resizew, hResizes the image (reductions below 1/2 are done in steps).
cropx, y, w, hCrops the image.
canvasw, h, anchor, backgroundChanges the canvas size (pixels are kept).
rotatedeg (multiples of 90)Rotates the image (lossless).
flipaxis: 'x' | 'y'Flips the image (lossless).
mosaicx, y, w, h, strength (0–100)Applies a mosaic to a region.
fillx, y, w, h, colorFills a region with a colour.
A working example is demo/en/image-resize.html — five sample images of mixed sizes, adjustable cap, format and quality, and a before/after table of pixels and bytes. Text, shapes, drawing, colour adjustment, filters, free rotation and frames work the same way (the bundled edition is 2.2); the full operation reference is in the DEXT Image integration API manual (supplied separately).

9-H. Approval / application form field engine approvalform add-on v2.6.6

Load dist/plugins/approvalform.min.js and add 'approvalform' to plugins (opt-in, about 23 KB). It is the first plugin built on the DOM API (§7): watch · silently · duplicate.

9-H-1. Why

The editor produces HTML. "Supply amount 100,000" on an expense form is, to the editor, text inside a table cell — but aggregation and approval need the value. Re-parsing the saved HTML breaks as soon as a user deletes a row. This plugin reads tags on the form's cells to extract values, fill computed cells, validate before submission and add or remove tagged rows. We recommend saving { html, fields }; aggregation reads fields only.

9-H-2. Field convention

AttributeValueMeaning
idaf-dept · af-items-1-supplySpecifies the handle for the DOM API. A single field uses af-<name>, and a repeating row uses af-<row>-<n>-<col>.
data-af-fielddept · items[].supplySpecifies the JSON key. [] marks a repeating row, which becomes an array.
data-af-typetext · number · date · check · select · blockblock is a free-form area such as a body (see 9-H-2-1). For other types, it specifies the normalization: "118,000" → 118000, localized dates → 2026-09-10, and ☑ → true.
data-af-formulaitems[].supply * 0.1 · SUM(items[].total)Marks a computed cell; pair it with contenteditable="false". Inside a row, items[].x means this row; outside, it means the whole column (an array).
data-af-required—Reports an error if the field is empty at submission.
data-af-optionsAnnual,Half-day,SickSpecifies the options for select. Any other value is reported as an error.
data-af-min · data-af-max0 · 2026-12-31 · from · periods[].fromAdded in v2.6.8. Specifies the range of a number or date field: a fixed value or another field key (a repeating-row column means the cell in the same row). A value outside the range is reported as an error at submission (af.errMin · af.errMax, or af.errMinDate · af.errMaxDate for dates; the error's bound holds the limit). For example, data-af-min="from" on an end-date cell prevents submission when the end date is before the start date. When the referenced cell is empty, that range is skipped.
data-af-rowitemsMarks a repeating row, as in <tr id="af-items-1" data-af-row="items">.

Formulas never use eval; a built-in parser supports + - * / %, comparisons, && || !, strings and SUM COUNT MIN MAX ABS ROUND IF DAYS WORKDAYS. WORKDAYS(from, to) skips weekends and options.approvalForm.holidays.

Input cell background v2.6.8. When a form is attached for writing (loadApprovalForm(html)), the cells people fill in (not formula or signature cells) get a pale yellow background (#fff8db) so input fields stand out. Change it with approvalForm: { inputColor: '#e0f2fe' } and turn it off with inputColor: false. Only a marker on the editor frame is added and the body HTML is left untouched, so read-only views ({ readOnly: true }), printing and saved HTML have no color. The form designer (§9-H-4) canvas and preview use the same color.

9-H-2-1. Multi-line fields — free-form area (block)

A field that takes several lines, lists, tables or pictures — a body, say — should be a container for paragraphs (<div data-af-type="block">), not a paragraph (<p>). Pressing Enter in a paragraph field makes the browser split the paragraph and copy its id, creating a duplicate id. Inside a container only the inner paragraph splits, so the field stays single.

<!-- Example: free-form area -->
<div id="af-body" data-af-field="body" data-af-type="block" data-af-required>
  <p>We propose to proceed as follows.</p>
</div>
SituationBehaviour
Value of a free-form areaThe text with a line break for each paragraph and <br> ("line 1 line 2"). The required check passes if it contains a picture or table, even without text.
Enter in a paragraph field (<p>)Turns the field into a free-form container and adds a paragraph inside, so existing forms accept several lines too.
Enter in a text field (<span>)Inserts a line break (<br>) inside the field — for example a second attachment line.
Enter in a number, date, select or check fieldEnter is ignored (these are single-value fields).
Backspace at the very start, Delete at the very endThese keys are blocked so that text is not merged out of or into the field.
A field split by pasting or in an older documentCopies with the same id that sit right next to each other are merged back (when the document opens, when it changes and before the submission check). Only duplicates elsewhere are reported as a duplicate id.

9-H-3. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/approvalform.min.js"></script>

const editor = new WebEditor('#editor', {
  plugins: ['format', 'table', 'approvalform'],
  approvalForm: { debounce: 150, holidays: ['2026-10-03', '2026-10-09'] },
});

editor.loadApprovalForm(formHtml);            // load and start watching — empty computed cells get filled

editor.on('approvalform:change', ({ fields, changed }) => { … });   // changed cell ids + values after computing

// submit
const r = editor.validateApprovalForm();     // { ok, errors:[{ id, field, label, row, reason, message }] } · marks cells with .we-af-invalid
// label = the field's name (header cell text · title) · row = which repeating row — show label, not the id (af-dept), to users
if (r.ok) save({ html: editor.getSafeHTML(), fields: editor.getApprovalFields() });

// rows
editor.addApprovalRow('items');      // duplicate() with renumbered ids · the new row's formulas are filled by watch
editor.removeApprovalRow('items');   // the last row is kept

// attach/detach watching on content already loaded · recompute every formula
editor.attachApprovalForm({ readOnly: false });
editor.detachApprovalForm();
editor.recalcApprovalForm();

// viewer — no computing (values were fixed at submission)
editor.setReadOnly(true).loadApprovalForm(doc.html, { readOnly: true });
The toolbar gains [Add form row] [Remove form row] (acting on the row under the caret; command names afAddRow · afRemoveRow for a custom toolbar array). When the form has a single repeat-row group (data-af-row), a row is added at the end of that group even if the caret is outside the table; for forms with no repeat rows (draft, notice, …) both buttons are greyed out while writing. The approvalform:change detail is { fields, changed, errors } — changed holds the ids of the cells that changed, and errors holds any errors that occurred while computing. Computed cells are shown in grey and invalid cells in red. Only formulas depending on the changed cell are recomputed, so a form with hundreds of fields does not recompute everything per keystroke. Demo: demo/approvalform.html (Korean package).
An approval-workflow example built on it (draft memo · expense report · leave request · approval line · signature cells that follow the line · budget/leave aggregation): demo/approval/index.html (Korean package; runs on localStorage without a server).

9-H-3-1. Static helpers — ApprovalFormPlugin

These calculation and formatting tools work without an editor. You can use them to re-check values on the server with the same rules as the screen.

ParameterDescription
ApprovalFormPlugin.formula{ parse, evaluate, refsOf, tokenize, functions } — the formula parser and evaluator (no eval). functions lists the usable functions (SUM · ROUND · IF · MIN · MAX · ABS · COUNT · WORKDAYS · DAYS).
ApprovalFormPlugin.normalize(text, type) · format(value, type)Converts cell text to a value (number, date, check, select) and back. Unreadable text returns { error }. For example, '118,000' → 118000, 'Sep 10, 2026' → '2026-09-10'.
ApprovalFormPlugin.workdays(from, to, opts)Counts working days (weekends and holidays excluded, opts = { weekend, holidays }).
ApprovalFormPlugin.parseBound(spec, type) (v2.6.8)Reads a data-af-min / data-af-max value (fixed value, another field key, or a column in the same row) → { value } (number or date) · { key } (field) · { error } (unreadable) · null if empty.
ApprovalFormPlugin.INPUT_COLOR · INPUT_SEL (v2.6.8)Default background of input cells while writing (#fff8db) and the input-cell selector (formula and signature cells excluded), so you can use the same color on your own screens.

9-H-4. Form designer approvaldesigner add-on v2.6.8

Lets you build forms that follow the 9-H-2 convention without writing code. Draw the table in the editor, select a cell and set its field properties (key · type · required · options · formula) in the panel. Ids are made from the key (af-dept · af-items-1-supply), and renaming a key updates the formulas that use it. Formulas are checked with the field engine's parser and are not applied if they contain errors. Use it together with the field engine (approvalform).

<script src="dist/plugins/approvalform.min.js"></script>
<script src="dist/plugins/approvaldesigner.min.js"></script>
const ed = new WebEditor('#designer', { plugins: ['format', 'table', 'insert', 'approvalform', 'approvaldesigner'], tableLock: false });
ed.openFormDesigner({ html: ApprovalDesignerPlugin.blankHtml('Travel expenses'), panel: '#panel' });
// pick cells and set fields in the panel, or in code:
ed.setFieldProps('af-supply', { type: 'number', required: true });
const def = ed.getFormDefinition({ name: 'Travel expenses' });   // { name, html, fields, rows } — save it on your server

To start from a Hangul or Word approval form your company already uses, load the import plugins (hwpimport · hwpximport · wordimport) too. To move a form to another PC or customer, export and import it as a JSON file.

<script src="dist/plugins/hwpximport-native.min.js"></script>   <!-- .hwp: hwpimport-native · .docx: wordimport-native -->
await ed.importFormDocument(file);                 // replaces the body, then tidies tables and adds the signature table → { ok, tidy, sign }
const json = ed.exportFormJson({ name: 'Travel expenses' });
const [form] = ApprovalDesignerPlugin.parseFormJson(json);   // strips unsafe parts of the html; fields are extracted again from the html
ParameterDescription
openFormDesigner({ html, panel })Opens designer mode. panel is the element or selector for the field property panel; without it, the panel is created right below the editor.
closeFormDesigner()Closes designer mode (removes the panel and the dashed field outlines).
selectFormField(key)Moves the caret to the field cell with that key and shows it in the panel. Returns false if there is none.
setFieldProps(target, props)Sets field properties on a cell (id or element). props is { key, type, required, options, formula, num, min, max }; items you leave out stay as they are. An empty key is suggested from the header cell text. Returns { ok, id, key } or { ok:false, error } (duplicate key · key not in Latin letters · invalid formula).
clearFormField(target)Removes the field properties.
lockFormHeaders()Locks every header cell (td.h · th) that is not a field and returns how many were locked.
insertSignPlaceholder()Inserts the signature table placeholder (table.sign) below the title. Returns false if one already exists.
listFormFields() · getFormDefinition(meta)Return the field list and the form definition ({ ...meta, html, fields, rows }). html is the source; fields and rows are its summary.
markRepeatRow(target, name) · unmarkRepeatRow(target)Makes a table row a repeating row or unmarks it. Field keys in the row become name[].column, and their ids and the formulas that use them are updated accordingly. Header (thead) / footer (tfoot) rows and two names in one table are not allowed.
lintForm() · fixForm(codes?)Returns checks L01–L13 (duplicate id · duplicate key · formula error · missing field · cycle · id/repeating-row convention · select without options · editable formula cell · no signature table · no fields · unlocked header cells · report keys · L13 range rules — an unreadable value, a missing field or a column from another row is an error, a range on a cell that is not a number or date is a warning) as [{ code, level, message, fix }]. fixForm fixes those that can be fixed (L01 · L06 · L08 · L09 · L11) and returns the number fixed.
previewForm()Opens the preview dialog, where you can try values, formulas, adding rows, checks and extracted values with the field engine (nothing is saved to the form). Uses contentCSS and preview.approvalForm (holidays etc.) from openFormDesigner.
importFormDocument(file, opts?)Imports an HWP · HWPX · DOCX document as the body (the import plugin for that format must be loaded), then runs tidyForm() and inserts the signature table placeholder. Returns Promise<{ ok, tidy, sign }>. opts.tidy:false skips tidying. Other formats or a missing plugin are rejected with an error.
tidyForm(opts?)[Tidy tables]: adjusts imported tables to fit the form convention. Unwraps nested tables (single-cell wrappers · "title | approval box" layout tables), turns a table whose first cell is the approval caption (Korean gyeoljae) into the signature table placeholder, marks cells with text as header cells (td.h), leaves empty cells as field slots, turns the first row of a list table into thead, and removes widths, borders and fonts. Cells with guide text (____ · ☐) stay value cells. Cells that are already fields are left unchanged. Returns { flat, sign, heads, thead, strip, title }.
useTableAsSign(target?)[Use as signature table]: replaces the table holding the cell (or the cell picked in the panel) with the signature table placeholder. Returns { ok:false, error } for a table with fields or when a signature table already exists.
exportFormJson(meta) · ApprovalDesignerPlugin.formJson(def)Returns a form file (JSON string): { format: 'dee-approval-form', v: 1, exportedAt, form: { name, icon, desc, css, version, html, fields, rows } } (forms for several). The form id and status are not included.
ApprovalDesignerPlugin.parseFormJson(text)Reads a form file and returns [{ name, icon, desc, css, html, fields, rows, sourceVersion }]. Scripts, frames, event attributes and javascript: URLs are removed from the html, and fields · rows are extracted again from the html instead of trusting the file. Throws an error if the file is not a form file.
ApprovalDesignerPlugin.templateHtml(document HTML) · .sanitize(html) · .tidyHtml(html)Turn a document template (a full HTML document) into form HTML (body only · unsafe parts removed · tables tidied · signature table below the title) · remove unsafe parts only · tidy tables only (no editor needed).
approvaldesigner:change eventFires with { fields } whenever a field is set or changed.
The approval example's Admin › [Form management] (demo/approval/designer.html, Korean package) is built on this add-on. Only published forms appear on the writing screen, and changes made after publishing reach users once the form is published again. Forms are checked before publishing and are not published while errors remain. The list can start from [Import document (HWP · HWPX · DOCX)] · [Start from template] (demo/templates/) · [Import JSON], and each row has [Export]. An imported JSON form is added as a draft, so please open it and publish it again.

9-I. Hangul HWP (.hwp) import API v2.6.7.0

To use it, load dist/plugins/hwpimport-native.min.js and list 'hwpimport' in plugins (opt-in). It reads Hangul binary .hwp (HWP 5.x) files. It is separate from the HWPX plugin (9-A). The formats differ (.hwpx = ZIP + XML, .hwp = OLE compound file + compressed records), so the engines and bundles are separate and you can load either one on its own.

Most public-sector and corporate documents in Korea are still .hwp. No server, no Hangul installation on the user's PC and no external library is needed. Reading the OLE compound file and inflating the streams are implemented in the browser, so it works on closed networks.

9-I-1. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/hwpximport-native.min.js"></script>   <!-- .hwpx (optional) -->
<script src="dist/plugins/hwpimport-native.min.js"></script>    <!-- .hwp -->
const editor = new WebEditor('#editor', {
  plugins: ['format', 'image', 'table', 'link', 'hwpximport', 'hwpimport']
});

// The unified "Import document" button and drag & drop work by themselves. In code:
await editor.importDocumentFile(file);                        // picks the module by extension
await editor.importHwpFile(file, { silent: true, mode: 'replace' });

9-I-2. One button — the extension picks the module

Entry point.hwp.hwpx
The unified "Import document" button · menu bar File › Import documenthwpimport → importHwpFile()hwpximport → importHwpxFile()
Dropping a file on the editor
editor.importDocumentFile(file)
The file picker lists only the extensions of loaded plugins — .hwp appears only when hwpimport is loaded. Dropping a .hwp without the plugin shows the "to import this format …" notice (9-F). Where per-format buttons are used, the command name is hwpImport (placed just before the HWPX button). When several files are dropped at once, only the first document is imported and a notice lists the ones that were skipped (this applies to every document import).

9-I-3. importHwpFile options

OptionTypeDefaultDescription
mode'cursor' | 'append' | 'replace''cursor'Specifies where to insert. With 'cursor', an empty paragraph holding the caret is replaced. A paragraph with text is not split; the content is inserted after it.
silentbooleanfalseWhen true, the content is converted and inserted immediately, without the options dialog.
imagesbooleantrueWhen false, pictures are kept as base64 instead of being passed to uploadHandler.
maxTableWidthnumber—Specifies a width (px). Tables wider than this are scaled down proportionally.
To convert without an editor, call await HwpImportPlugin.convert(arrayBuffer), which returns { html, warnings, info, previewOnly }. To check whether a file is HWP first, use HwpImportPlugin.sniff(arrayBuffer).

9-I-4. What is converted (HWP 5.x → HTML)

SourceResult
Character formattingPer-language fonts, size, colour, bold / italic / underline / strike, super / subscript, shading, letter spacing and text shadow (text-shadow) are preserved. Heavy display fonts are also given font-weight:bold so that they still look bold on a PC without the font. Extreme negative letter spacing is limited to −10% so that glyphs do not overlap.
Paragraph formattingAlignment, left / right margins, first-line / hanging indent, spacing before / after, line spacing and numbering / bullets are preserved.
TablesMerged cells, column widths (<colgroup>), per-side borders (including the table’s own border; the outer edge is drawn as Hangul does even where the edge cells have no border), fills, cell padding, vertical alignment, nested tables, table captions (as a paragraph above / below the table) and the position of tables indented with spaces or tabs are preserved.
PicturesJPG · PNG · GIF · BMP pictures are uploaded through uploadHandler (BMP is converted to PNG first).
Pictures embedded as OLE objects (a logo pasted from Paint, Photo Editor and the like)The object's presentation picture — exactly what Hangul draws on screen — is extracted and inserted as a PNG. The object's native data is never read. An object drawn with lines and text only (a chart) holds no bitmap, so it is left out and reported as a missing picture.
Seals and signatures (pictures placed behind / in front of text)They are placed at their original coordinates, overlapping the text. They are not absolutely positioned. Each is an ordinary <img> that takes up no room (a float), so the text is not pushed aside and shows over the picture, and the picture can still be selected, moved or deleted in the editor. It survives in the saved HTML.
Grouped shapes and rectangles that contain text (title boxes)Header decorations such as a logo plus a dotted rounded box, or a white box over a shadow box, are imported with line, fill, rounded corners and the text / picture inside, in their original arrangement. Spacing above / below the object and its indent follow the original too.
OtherPage breaks, footnotes at the end of their page (a small-type box under a short rule — pages that overflow automatically, with no page-break record, are detected from the stored line positions), endnotes at the end of the document, landscape documents, runs of spaces used for alignment (the characters are left as they are and kept with white-space:pre-wrap — a non-breaking space prints as an empty box in some Korean fonts) are preserved as well.
Objects that are not imported — shapes without text (lines, ellipses, polygons) · charts · OLE objects that hold no bitmap · WordArt · headers / footers · multi-column layout · pictures browsers cannot draw (WMF, EMF, TIFF). The notice shown after import gives the number of objects that were skipped.

9-I-5. Supported HWP versions

DocumentSupportBehaviour
HWP 5.0.x – 5.1.x (.hwp saved by Hangul 2002 – 2024)✅ SupportedBody, formatting, tables and pictures are imported, for both compressed and uncompressed files. Verified versions: 5.0.2.4 · 5.0.5.0 · 5.1.1.0.
Distribution documents (published read-only)△ text onlyThe body is encrypted, so only the document's preview text is imported, with a notice saying so.
Password-protected❌The import stops with "password-protected documents cannot be opened". Please remove the password in Hangul, save the file, and try again.
HWP 3.0 or older (Hangul 97 and earlier)❌The file structure is completely different. It is recognised, and the user is asked to re-save it in Hangul (.hwp or .hwpx) or to copy and paste from Hangul — pasting works for 3.0 documents too (3-4).
An HWPX file named .hwp—A notice asks you to "rename it to .hwpx".
HWP 6 or any other major version❌The import stops with "unsupported HWP version" and shows the version number.
Unreadable documents never fail silently. The import stops with a reason, or the notice says that only the preview text was imported. A structurally damaged file is handled the same way when it contains preview text.

9-I-6. Security and robustness

  • This feature opens files created by others, so cycles in the OLE sector chains and directory tree are guarded against, and the inflated size has a ceiling (against zip bombs). If it is exceeded, the import stops.
  • Document macros (Scripts/*) are never read. For an OLE object the native data is never read; only the single presentation-picture stream in its storage is read, within a size ceiling, to extract the bitmap. There is no path that executes anything.
  • Pictures are identified by their signature, not their extension. The generated HTML goes through the same sanitising path as every other import, and all text is escaped.

9-I-7. Related features

FeatureDescription
Copy and paste from HangulThis is handled by the core, with no plugin needed: cell alignment, fonts, column widths, colour bands and pictures (recovered from the clipboard's RTF). It works even for HWP 3.0 documents that cannot be imported. Refer to 3-4.
Attachment [Preview]The distribution's demo board page doc-preview.html opens a .hwp attachment in a new window as content (using hwpimport). The JSP and React board samples do the same.

9-I-8. Known issue — the file dialog disappears on some PCs

On some PCs the Windows file dialog vanishes as soon as the mouse hovers over a .hwp file (Chrome, Edge and even Notepad, before [Open] is pressed). The shell extension that an older Hancom Office (e.g. 2014) registers for .hwp crashes while building the hover tooltip inside the browser that owns the dialog. This happens before any editor code runs, so the editor cannot prevent it; it began to appear in v2.6.7.0 because the dialog now lists .hwp files.

  • Workaround: drag the file from Explorer onto the editor (no file dialog involved), or copy from Hangul and paste. The import dialog shows this hint, and when a file dialog that lists .hwp closes without a file, the editor shows it once as a notice (a vanished dialog and a user cancel look the same, so the notice says “if the dialog closed by itself”).
  • Fix (user PC): update Hancom Office, or turn off Explorer → View → Options → View tab → “Show pop-up description for folder and desktop items”. An IT department can instead disable just that shell extension (HncShellExt64.dll).
  • How to confirm: in Notepad, choose [Open] and hover over a .hwp in the same folder. If that dialog also disappears, this issue is the cause. .hwpx, .docx and other formats are unaffected.
This product was developed with reference to the HWP document file format specification published by Hancom Inc. A summary of the method is also in the importHwpFile card under 3-7.

9-J. PDF import API Beta v2.6.7.0

To use it, load dist/plugins/pdfimport-native.min.js and list 'pdfimport' in plugins (opt-in). A PDF is imported not as a picture but as editable content (paragraphs, headings, lists, tables, pictures). What is built in (the editor alone) and what is added with DEXT-PDF (a separate product) are described in 9-J-0.

9-J-0. What is built in and what DEXT-PDF adds

PDF import has a built-in feature set that needs only the editor, and features that are added when the separate product DEXT-PDF sits alongside it. The built-in set is handled by Dee Editor's own engine (Type 1); with DEXT-PDF present, the engine that takes DEXT-PDF's structure analysis (Type 2) is used instead. The calling code (importPdfFile) is the same.

Built in Type 1 'native'With DEXT-PDF Type 2 'dext-pdf'
What you needdist/plugins/pdfimport-native.min.js alone, which is included in the standard distribution The left column plus the DEXT-PDF runtime folder dext-pdf/. DEXT-PDF is a separate product, supplied as an integration package to customers who request it. dee-editor-v<version>-Enterprise.zip contains dext-pdf/ and dext-ocr/
How to switch it on'pdfimport' in plugins Put dext-pdf/ next to dist/ and it is used automatically (engine:'auto', the default). If it is elsewhere, set pdfImport.dextPdfUrl
Structure analysisDee estimates it from character positions, sizes and ruled lines DEXT-PDF analyses it (a tagged PDF follows its tags). Dee fills in what is missing or incorrect
What worksText → paragraphs, headings, bold, italic, superscript, links · lists · ruled tables (merged and shaded cells) · forms drawn with ruled lines · two-column reading order · running headers/footers removed · pictures (JPEG, PNG) · scanned pages as page pictures · encrypted documents Everything built in, plus the items below
Added with DEXT-PDF— Nested lists · highlighted, underlined and struck-through text (annotations) · every page as a page picture (importMode:'image') · a page picture where text cannot be read · vector shapes and charts as pictures · JPX, JBIG2 and CCITT pictures · leaving out a certificate's background picture and splitting its label lines (0.4.8+) · real progress and cancelling midway
Without DEXT-PDF— With 'auto', the built-in engine (Type 1) runs instead. If you set engine:'dext-pdf' explicitly, an error is reported (so that a configuration mistake is not hidden)
The import dialog shows the engine in use under "Conversion engine", and you can switch there to compare. Each item in 9-J-5 and 9-J-6 below is also marked Built in / With DEXT-PDF. For placing the DEXT-PDF runtime and server settings, see the external module integration manual.

9-J-1. Why Beta — what to expect and what to check

A PDF has no paragraphs. It only has instructions to draw text at coordinates. DOCX, HWP and XLSX files contain their own structure (paragraphs, tables, cells), which is simply preserved; a PDF's paragraphs, headings, lists and tables are all estimated from coordinates, type sizes and the position of lines. The estimate is accurate for ordinary documents but can be wrong for unusual ones. That is why v2.6.7.0 ships it as Beta.

What Beta means hereDescription
Compare the result with the originalAfter importing, put the original PDF beside the result and check tables, reading order and missing text. What was removed or replaced is listed in the notice shown after import (showLog:true shows every warning).
An empty result rather than a wrong oneOn a page whose text cannot be read (fonts without a character map), garbled text is never inserted. The page is skipped with a warning or inserted as a page picture. This principle will not change after Beta.
Results may improve from version to versionThe estimation rules (paragraph breaks, table detection, two-column order, form tables) are still being tuned against real documents. The HTML produced from the same PDF may differ in a later version, so avoid post-processing code that depends on the exact shape of the imported HTML (tags, classes).
What is not going to changeThere is no plan to change the method name importPdfFile, the names and meanings of the options below, the plugin name 'pdfimport', the bundle file name or the container class we-pdf-doc. Calling code can stay as it is.
Type 2 follows the DEXT-PDF versionThe quality of Type 2 depends on the version of the DEXT-PDF runtime placed beside the bundle. The improvements for certificates and forms need 0.4.8 or later (9-J-5).

9-J-2. Basic usage

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/pdfimport-native.min.js"></script>
const editor = new WebEditor('#editor', {
  plugins: ['format', 'image', 'table', 'link', 'pdfimport']
});

// The unified "Import document" button, drag & drop and menu bar File › Import PDF… work by themselves. In code:
await editor.importPdfFile(file, { importMode: 'auto', pageBreaks: false });
await editor.importPdfFile(file, { silent: true, mode: 'replace', pages: [1, 2, 3] });

The file is never sent to a server. Everything is converted in the browser, so it works on closed networks. Documents with an open or permissions password (RC4, AES-128/256) can be opened too; you are asked for the password when it is needed.

9-J-3. importPdfFile options

OptionDefaultDescription
modedialog: 'cursor' · silent: 'cursor''cursor' / 'append' / 'replace'
silent · showLogfalseIndicate, respectively, whether the dialog is skipped and whether every conversion warning is shown.
pagesallSpecifies the page numbers to import (1-based). In the dialog, you enter them as "1-5, 8".
importMode'auto'Specifies the import mode. 'auto' imports text pages as content and scanned pages as pictures, 'text' imports text only, and 'image' imports page pictures. Type 1 can turn only scanned pages into page pictures; to import text pages as pictures, Type 2 is required. If there is nothing to insert, the body is left unchanged and a notice explains why.
pageBreaksfalseIndicates whether a page break is inserted at each page boundary. When off, a paragraph that runs across pages is joined.
headerFootertrueIndicates whether running headers, footers and page numbers are removed.
password—Specifies the open password. If omitted, you are asked for it when needed.
engine'auto'Specifies the engine: 'native' (Type 1) · 'dext-pdf' (Type 2) · 'auto'. 'type1' · 'type2' · 'both' mean the same. Refer to 9-J-4.

9-J-4. Two engines — built in (Type 1) and with DEXT-PDF (Type 2)

Built in Type 1 'native'With DEXT-PDF Type 2 'dext-pdf'
What it isDee Editor's own parser. It needs no external library and is always available.It uses the structure analysis of the DEXT-PDF runtime (dext-pdf/). It is available only when the runtime is present.
Who works out the structureDee (lines, paragraphs, headings, lists, tables and two-column order are all estimated)DEXT-PDF works out the structure (a tagged PDF follows its tags). Dee fills in what is left empty and rebuilds pages whose structure was analysed incorrectly.
What it adds—It adds highlighted / underlined / struck-through text (annotations), every page as a picture, a page picture where text cannot be read, vector shapes and charts cut out as pictures, leaving out a certificate's background picture, and real progress and cancelling midway.
// whole site — webeditor-configuration.js (loaded before the bundle)
window.WebEditorPdfImportEngine = 'both';   // 'type1' built-in only · 'type2' DEXT-PDF only (an error if missing) · 'both' (default)

// per editor / per call
new WebEditor('#editor', { plugins: ['pdfimport'], pdfImport: { engine: 'auto', dextPdfUrl: '/dext-pdf/dext-pdf.js' } });
editor.importPdfFile(file, { engine: 'dext-pdf' });
Precedence: the engine passed to importPdfFile > the editor option pdfImport.engine > the global setting > 'both'. The runtime is looked for at ../dext-pdf/dext-pdf.js relative to the core bundle (webeditor.min.js) (or at dextPdfUrl) and loaded on first use; no DEXT-PDF code is included in the Dee bundle. You can switch engines under "Conversion engine" in the dialog to compare. For runtime placement, features by version and server settings, see the External Module Integration Guide.

9-J-5. What is converted

SourceBuilt inAdded With DEXT-PDF
TextLines become paragraphs, and headings (by type size), bold, italic, superscript and links are preserved. Korean line joining is applied (a line broken between characters is joined without a space).Highlighted, underlined and struck-through text (annotations)
ListsBullets (characters and drawn shapes) and numbered lists are preserved.Nested lists
TablesRuled tables are imported with merged cells, column widths, header rows, shaded cells and right-aligned amounts. Forms drawn with ruled lines (tax forms, application forms) are imported as tables too, and small boxes standing on their own inside a large cell become nested tables. Cell borders are not read as blank underlines.A tagged PDF follows the table structure in its tags
LayoutThe reading order of two-column text, side-by-side "label : value" forms, removal of running headers, footers and page numbers, and joining paragraphs across pages are handled.A tagged PDF follows the reading order in its tags
PicturesJPEG pictures are kept as they are and everything else is converted to PNG. Both are uploaded through uploadHandler. Scanned pages become page pictures (figure.we-pdf-page).JPX, JBIG2 and CCITT pictures · vector shapes and charts cut out as pictures · every page as a page picture (importMode:'image')
Certificates—A pale background picture in the middle of the page (a seal watermark) is left out and reported. Each "label : value" pair gets its own line. Fragments containing only ':' are removed (DEXT-PDF 0.4.8+)
The container is <div class="we-pdf-doc">, tables are .we-imported-table.we-pdf-table, two-cell form tables are .we-pdf-form, and scanned pages are figure.we-pdf-page. Results by kind of document are in the "Forms and certificates" table of the importPdfFile card under 3-7.

9-J-6. Limits

  • Fonts without a character map (ToUnicode) — text in legacy CID fonts or Type3 fonts cannot be read. Built in, such a page is skipped with a warning; With DEXT-PDF, it is inserted as a page picture. This is also why a few symbols may be missing from an otherwise readable form.
  • Tables without lines (aligned with spaces only) come in as paragraphs. Vertical writing is not supported (both engines).
  • Vector shapes and charts and JPX, JBIG2 or CCITT pictures cannot be imported Built in (they are left out). With DEXT-PDF, they are imported as pictures.
  • Form fields (AcroForm), annotation notes, bookmarks, attached files and layers are not imported (both engines). Type sizes and positions are re-laid to fit the flow of the content, so the result does not look like the original page. When the page must look the same, use importMode:'image' With DEXT-PDF. Built in page pictures work for scanned pages only.
The attachment [Preview] page (doc-preview.html) converts a PDF through the same path when pdfimport is loaded, and falls back to the browser's PDF viewer (<iframe>) when it is not.

9-K. Table and cell lock

This feature protects tables with a fixed layout, such as approval documents and application forms. By default, tables use automatic layout (table-layout:auto), so long text without spaces (such as a document number) makes the browser widen that column and shrink its neighbours, which distorts the table. Adding the lock marker data-we-lock to a table or cell fixes the column widths, blocks edits that change size or structure, and blocks text editing in cells that must not change. This feature is part of the core, so you do not need to load an extension.

9-K-1. Lock levels

ValueDescription
size (or 1)Size and structure lock. Column widths no longer follow the content, and long text wraps inside the cell. Text stays editable.
readonly (or 2)Size, structure and editing lock. Blocks everything that size blocks, as well as text editing and cell formatting (background, borders, alignment).

On a table (<table>), the lock covers the whole table; on a cell (<td> · <th>), it covers only that cell. A cell's lock is combined with its table's lock, so if the table is readonly, every cell is locked for editing. Tables nested inside a locked table are treated as locked too.

9-K-2. What a locked table blocks

EditIn a locked table
Typing long text into a cellThe column width stays the same, and the text wraps inside the cell (in the editor, preview and viewer alike).
Dragging a cell border or the table cornerThe resize cursor and handle do not appear. When you hover, a 🔒 badge is shown instead of the handle.
Inserting or deleting rows and columns, merging and splitting, equalizing cell sizes, deleting the tableThe right-click items are greyed out, and the menu bar and ribbon commands only show a "This table is locked" notice.
Tab in the last cellNo row is added.
Pasting a tableThe table is not enlarged and merges are not split; only existing cells are filled. Cells locked for editing are skipped.
Delete or cut on several selected cellsCells locked for editing are not cleared.
Actions that keep the layout intact still work, such as copying, editing text in other cells, and [Add form row] on approval forms (9-H), which only duplicates the rows the form defines.

9-K-3. Writing it into form HTML

The lock is saved in the HTML as the data-we-lock attribute. If you add the attribute to a form template, the document opens locked every time it is loaded.

<!-- Example: form HTML — the table locks size and structure, label cells lock editing -->
<table data-we-lock="size">
  <tr>
    <td data-we-lock="readonly">Document no.</td><td></td>
    <td data-we-lock="readonly">Effective date</td><td></td>
  </tr>
</table>

The editor adds contenteditable="false" to cells locked for editing, but getHTML() removes it, so the saved HTML contains only data-we-lock (on approval-form formula cells, data-af-formula, it is kept as part of the form definition, as of v2.6.8). The viewer stylesheet (dist/webeditor-content.css) includes the same width rule, so posted documents also keep their column widths.

9-K-4. Locking and unlocking from the API

MethodDescription
setTableLock(target, mode)Locks or unlocks a table or cell. mode is 'size', 'readonly' or null (unlock). Locking a table records the column widths shown at that moment in a <colgroup>, so locking does not change how the table looks. Returns true when applied.
getTableLock(target)Returns the lock state ('size', 'readonly' or null). For a cell, the table's lock is included.

target accepts an element, an APIModel, an id, or a selector starting with #, . or [. An element inside a cell is treated as that cell. See setTableLock() for details.

// Example: the API
editor.setTableLock('#form-table', 'size');      // lock size and structure
editor.setTableLock('label-docno', 'readonly');   // lock editing of one cell, by id
editor.getTableLock('label-docno');                // 'readonly'
editor.setTableLock('#form-table', null);        // unlock

9-K-5. The tableLock option — per screen

ParameterDescription
tableLocknull (default) honours lock markers and hides the lock menu. false ignores lock markers (the previous behaviour).
tableLock.menuWhen true, adds [Table lock] to the table right-click menu (lock size · structure, lock all editing, lock / unlock selected cells, unlock). We recommend turning it on only on form-design screens (admin, form designer). The default is false.
tableLock.showIconSets whether hovering over a locked table shows a 🔒 badge instead of the resize handle. The default is true.
tableLock.allowSourceViewWhen false, the HTML tab is unavailable while the document has locked tables, so writers cannot remove the markers in the HTML. The default is true.
// Example: form-design screen — set and clear locks from the right-click menu
new WebEditor('#designer', { tableLock: { menu: true } });

// Example: writing screen — keep the locks and stop the markers being removed in the HTML tab
new WebEditor('#writer', { tableLock: { allowSourceView: false } });

9-K-6. Moving from another editor's table-lock settings

Table-lock settings from other editors (enabled, lock name, lock level, icon, HTML mode switching) map as follows. Lock values 1 and 2 are read as is, so you can reuse existing forms simply by renaming the attribute to data-we-lock.

Other editor's settingDee Editor
Table lock on or offThe tableLock option. It is on by default, and false turns it off.
Lock name (the attribute that marks a lock)Fixed as data-we-lock
Lock level 1 (resize lock) · 2 (resize lock + no editing)data-we-lock="1" · "2" (= size · readonly)
Show the lock icontableLock.showIcon
Whether switching to HTML mode is allowedtableLock.allowSourceView
The screen where locks are set (design mode)The right-click [Table lock] with tableLock.menu: true · setTableLock()

9-K-7. Example — approval forms

In the bundled approval sample (demo/approval/), the draft, expense report and leave request lock every table with size and lock the label cells (document no., effective date …) and approval headers with readonly. Long text in the document-number cell no longer widens it, label cells cannot be edited, and [Add form row] still adds item rows.

A lock blocks editing actions on screen; it is not a permission check. Saved HTML can be changed by other means, so we recommend also validating values that must not change (amounts, approval cells and so on) on the server.

9-L. Text recognition (OCR)

9-L-1. Overview

This feature reads printed Korean and English text in scanned documents, photos and scanned PDFs, and inserts it at the cursor as paragraphs and tables. Recognition runs inside the user's browser; images are not sent to a server. The engine is a separate product, DEXT-OCR; the editor provides only the connector plugin (ocr). The engine is supplied as a separate package to customers who request it. The PDF integration package dee-editor-v<version>-Enterprise.zip contains dext-pdf/ and dext-ocr/.

PartDescription
dist/plugins/ocr-native.min.jsThe connector plugin (opt-in, about 43 KB). It contains no engine or models.
dext-ocr/The DEXT-OCR engine (about 23 MB, including models, WebAssembly and pdf.js). If you place it next to dist/, the plugin finds it automatically, in the same way DEXT-PDF uses dext-pdf/.

For an overview of placement, server settings and connecting other engines in one place, see the External Module Integration Guide.

9-L-2. Setup

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/ocr-native.min.js"></script>
<script>
  const editor = new WebEditor('#editor', {
    plugins: [ /* default plugins */ 'pdfimport', 'ocr' ],
    ocr: { output: 'full' },            // optional
  });
</script>

The engine folder is looked up in this order. The engine is downloaded on first use (about 8–9 MB compressed), so it does not slow down opening the editor.

OrderLocation
1The ocr.dextOcrUrl option, which can be a folder (/dext-ocr/) or …/src/index.js
2The global WebEditor.dextOcrPath
3../dext-ocr/ relative to the core bundle (webeditor.min.js)
If the engine is not found or the browser is not supported (Chrome · Edge 91+ on PC, Chrome and Samsung Internet on Android, Safari 16.4+ on iOS and macOS; Internet Explorer is not supported), the text recognition items are hidden from the toolbar, menu and ribbon. The engine checks support before any model is downloaded, so unsupported phones never download the engine (about 7.7 MB). If you call the API anyway, it reports that the browser is not supported (or that the engine is not installed, if it is missing). Inside an app (WebView) that includes the DEXT-OCR Android or iOS library, the app's native engine is used automatically and no WASM or models are downloaded.

On a page without the engine, you can turn the search off. In that case, no request is sent to check the engine location (otherwise a single 404 line appears in the developer-tools console when the engine is missing), and the text recognition items are hidden. Engines registered with registerOcrProvider still work (v2.7).

WhereDescription
ocr: { dextOcrUrl: false }Applies to that editor only.
WebEditor.dextOcrPath = falseApplies to every editor on the page.
window.WebEditorDextOcrPath = falseIn a settings file loaded before the core (e.g. webeditor-configuration.js). The demo settings of an editor package built without the engine contain this line. Please delete it once you add dext-ocr/ from the separate package.

9-L-3. Use

Entry pointBehaviour
Toolbar · [File] menu · [File] ribbon — Text recognitionChoose an image (JPG, PNG, WebP …) or a scanned PDF, and it is inserted at the cursor page by page. The progress window appears in the middle of the document body, and the body is locked read-only until recognition ends (the toolbar and menus are disabled too). You can cancel from the progress window (Esc), and pages that have already been inserted remain.
Import DocumentWhen the engine is available, you can also choose image files, which are read as text.
Right-click an image — Extract text from imageShows the text in an editable window. Choose [Insert into document] (right after the image), [Use as image alt text] (accessibility alt) or [Copy].
Scanned pages in PDF importAfter scanned pages without text are inserted as images, the editor offers [Convert to text]. It replaces the page images with the recognition result (one Ctrl+Z step per page).

Ruled tables, and unruled tables with aligned columns, become editor tables, so cell editing, merging and borders work as usual. Undo is one step per page. Nothing is inserted into a read-only document.

9-L-4. API

APIDescription
editor.ocrInsert(file, { output, signal, privacy })Reads an image or scanned PDF and inserts it at the cursor. Returns Promise<{ text, html, pages, cancelled }>. Passing privacy overrides the ocr.privacy option for that call only (e.g. { privacy: { rrn: 'back' } } — extractTextFromImage takes it too).
editor.extractTextFromImage(input, { insert, output })Returns the result only. insert: 'none' (default) · 'body' · 'clipboard' · 'alt' (when input is an <img> in the document).
WebEditor.registerOcrProvider(adapter, { default })Connects another engine (such as an in-house server or a cloud service). The contract is described in the external module integration manual (OCR engine contract).
editor.setOcrProvider(name) · getOcrProviders()Chooses between engines. DEXT-OCR is named 'dext-ocr'.
EventArgument
ocrStart{ file, provider }
ocrProgress{ fraction, info: { stage, pageNo, pageCount } }
ocrPage{ pageNo, text }, fired each time a page is inserted
ocrDone · ocrCancel · ocrError{ pages, text } · { pages } · { error }

9-L-5. The ocr option

ParameterDescription
dextOcrUrlThe engine location (9-L-2). If omitted, it is found automatically. false turns the search off.
output'full' (default — paragraphs and tables) or 'text' (one paragraph per line; table cells joined with spaces).
hideWhenNoProviderHides the items when there is no engine (default true).
privacy{ rrn: 'back' | 'gender' | 'all' | false }. The engine masks Korean resident registration numbers before inserting (default false).
htmlTable HTML options; for example, { headerRow: true } turns the cells of the first table row into header cells.
ocrOptionsDEXT-OCR recognition options (pre · det · rec · layout). See the engine documentation.
Personal data: when the editor's privacy option (personal data detection) is on, inserting content that contains resident registration numbers, phone numbers, account numbers and so on shows a notice with [Review]. To mask the numbers in the engine before inserting, use ocr.privacy.rrn.

9-L-6. Server settings

ItemDescription
MIME.wasm → application/wasm · .mjs → text/javascript · .onnx → application/octet-stream. These are already set in the sample JSP board's web.xml.
IISIIS refuses any extension without a registered MIME type with 404.3 (a plain 404 in the browser). .mjs and .onnx are not in its default list, so without them text recognition stops with "Could not download the recognition engine". As in deploy/iis/web.config, put <remove> before each <mimeMap>. See "Text recognition (DEXT-OCR) setup notes (IIS)" in DEPLOY.md.
CSPIf you use a security policy, script-src 'wasm-unsafe-eval' and worker-src 'self' are required.
CachingThe engine rarely changes, so we recommend serving it from a versioned folder (/dext-ocr/0.2.0/) with long caching so that it is not downloaded again.
Compressed transferSee docs/deploy.md in the engine package for Tomcat, nginx, Apache and IIS. For Tomcat 7, we recommend placing Apache in front and using the Apache settings.
Recognition results can differ from the original. For documents that must be exact, such as official letters or contracts, check the inserted text against the original. Handwriting, vertical text and very small print (6 pt or less) may not be recognised well.

9-M. Tag clean-up (normalize) v2.7.1.0

9-M-1. Overview

While you type, the body HTML can collect empty <span>s, nested <span>s and styles that have no effect. When you join lines (Backspace · Delete), split them (Enter), paste, or apply font size or font to a selection again and again, the browser's editing area (contenteditable) wraps text in new <span style="…"> elements to keep the formatting. The text looks the same, but the HTML gets longer and deeper. This is mostly how the browser's editing feature behaves, and it builds up the more often the same content is edited. Spans nesting when the font size or font of a selection was changed repeatedly was an editor defect, also fixed in v2.7.1.0.

From v2.7.1.0, Dee Editor can clean up only the redundant tags whose removal does not change how the content looks. Each candidate is tested by removing it and comparing the computed style; it is removed only if the result is identical, so the screen looks the same before and after. Table structure, paragraph formatting, images, links, lists, class, id and data-* are kept unchanged (9-M-5).

PartDescription
Option autoNormalizeAutomatic clean-up while editing. Default true.
Option normalizeOnGetgetHTML() and getSafeHTML() clean up the whole body before returning. Default false.
editor.normalize(options?)Cleans up the current body and returns the counts.
getHTML({ normalize }) · getSafeHTML({ normalize })Decides whether to clean up once when reading the HTML.
WebEditor.normalizeHTML(html, options?)Static method for cleaning up content that is already stored, in bulk (migration · batch).

9-M-2. Options

ParameterDescription
autoNormalizeWhether to clean up automatically while editing (boolean, default true). Runs right after joining lines with Backspace · Delete, Enter, paste, drop, applying formatting to a selection (toolbar size · font · colour, Ctrl+B on a selection and so on). At the end of IME composition it applies only the structural fixes below (<p> wrapping · lifting blocks). It does not scan the whole body on every key; it tidies only the edited paragraph(s) and their neighbours. It also wraps top-level bare text (the first line typed into an empty editor) in <p> and lifts blocks that a browser editing defect placed inside a <p> back out. Typing plain characters alone does not trigger it. When the caret is collapsed (for example, Ctrl+B and then typing), the selection is not reset, so the pending "next character" formatting is kept. false restores the previous behaviour.
normalizeOnGetWhether getHTML() and getSafeHTML() clean up the whole body before returning (boolean, default false). No structural fixes (<p> wrapping · lifting blocks) are made. Turning it on makes the same content save as different HTML than before, so it is off by default; we recommend turning it on for new integrations.
// Options example
const editor = new WebEditor('#editor', {
  autoNormalize:  true,    // default — clean up while editing
  normalizeOnGet: true     // clean up the whole body when reading (default false)
});

9-M-3. API

normalize(options?) → object

Cleans up redundant tags in the current body and returns the counts (9-M-6). The caret and selection stay where they are. If anything changed, an undo record is pushed and the change event fires. Calling it twice finds nothing the second time.

ParameterDescription
structureWraps top-level text in <p> and lifts blocks out of <p>. Spacing may change by the <p> margin. Default false.
keepDefaultsKeeps declarations that would be removed only because they equal an inherited value (the editor's default font · size · colour · line height and so on). They are removed only when an outer element in the content sets the same property itself. Use this when the viewing page does not load the content CSS (dist/webeditor-content.css or getContentStyle()). Default false.
// normalize() example
const r = editor.normalize();
console.log(r.total, r);   // number of fixes · { styles, unwrapped, merged, removed, brs, wrapped, hoisted, zwsp, total }
editor.normalize();          // second run — total 0
getHTML(options?) · getSafeHTML(options?) → string

Decides whether to clean up once when reading the HTML. getSafeHTML() accepts normalize together with its existing options (allowedTags and so on).

ParameterDescription
normalizetrue runs normalize() first; false does not clean up. If omitted, the normalizeOnGet option decides.
structure(getHTML) Also applies the structural fixes when cleaning up. Default false.
// Clean-up on read example
const html = editor.getHTML({ normalize: true });
const safe = editor.getSafeHTML({ normalize: true });
const raw  = editor.getHTML({ normalize: false });   // no clean-up even if normalizeOnGet is on
WebEditor.normalizeHTML(html, options?) → string

A static method that returns the cleaned-up HTML string. Use it to clean up content that is already stored, in bulk (migration · batch). It decides by computed styles, so it works in the browser only; it briefly attaches a hidden work container to the page. Before that, it removes dangerous content with the same rules as sanitizeHTML().

ParameterDescription
editorUses this editor's body formatting (default font · size · content CSS) as the base. If omitted, the page's .we-body formatting is used.
structureSame as normalize(). Default false.
keepDefaultsSame as normalize(). Default false.

9-M-4. What is cleaned up

The items below are removed only when the look stays identical. Each one is removed on trial and the computed styles are compared; if anything differs, it is kept.

RuleDescription
1. Ineffective style declarationsOn formatting tags (span · font · b · strong · i · em · u · s · strike · small · sub · sup): declarations equal to the inherited value, browser-copy leftovers such as orphans · widows · font-variant-*, text-align on inline elements, and decoration colour or style when there is no underline or strike-through line. The remaining declarations keep their original text (#000000 is not rewritten as rgb(0,0,0)), so the HTML only gets shorter.
2. span · font without attributesUnwrapped; only the content remains.
3. Nested spansA span whose only child is a span is merged into one, only when the font family, size and line height are the same and there are no box properties. They are not merged when the outer element draws an underline or strike-through and the inner element changes the text colour, because the line colour would change. The merged declarations keep their original notation.
4. Adjacent same-looking elementsNeighbouring elements with identical tag and attributes are merged.
5. Empty formatting elementsRemoved when they have no box styles and the same font metrics as the parent. Empty elements that affect the line height are kept — for example when they contain a box element or an element of another size, shift the baseline like a superscript, or sit alone on the line after a <br> and so create that line.
6. Invisible trailing <br>A <br> at the end of a paragraph that has no visible effect is removed. Empty lines (<p><br></p>), consecutive breaks (<br><br>, including breaks separated by a formatting element or a space such as <b>end<br></b><br> and <br> <br>), a <br> after a block, a <br> inside an inline-block and a <br> after text that ends with a space are kept.
7. Caret placeholdersZero-width spaces (U+200B) that the editor inserted to hold the caret position are removed — only by normalize(), clean-up on output and normalizeHTML(); automatic clean-up while editing keeps them for the caret. They are not removed where that would change the display — when one holds up a line (its height) on its own, or sits right next to a space and keeps that space — nor inside pre, code or non-editable areas.
8. Structural fixes(autoNormalize, or structure: true) Top-level text is wrapped in <p>, and blocks inside a <p> are lifted out. An inline element that holds paragraphs (such as the <b id="docs-internal-guid-…"><p>…</p></b> that Google Docs pastes) is not wrapped in <p>, and when it sits inside a paragraph it is moved out of that paragraph as a whole (so the paragraphs do not split when the content is reopened).
<!-- Before / after example -->
<!-- before -->
<p><span style="font-size:14pt"><span style="font-size:14pt">Hello</span></span><span></span><br></p>
<!-- after -->
<p><span style="font-size:14pt">Hello</span></p>

9-M-5. Items excluded from clean-up

Clean-up targets only redundant elements on formatting tags. The following are kept unchanged, so tables and formatting are not affected.

ItemDescription
Table structuretable · tr · td, colspan · rowspan, table · column · cell widths
Paragraph formattingtext-align · line-height · indent · margins on blocks
Images · links · listsimg · a · ul · ol · li
Attributesclass · id · data-*. A formatting element carrying any attribute other than style is left as it is (font may also have face · size · color)
Code · math · graphicspre · code · svg · math
Non-editable regionscontenteditable="false" regions (for example, formula cells in approval forms)
Elements with box stylesElements with margin · padding · border · background-image · display · position · width · height and so on. Box-making declarations such as display:inline-block and transform are not removed even where the computed value looks the same (inside a flex container, for example), and empty formatting elements containing such elements are kept

9-M-6. Report

normalize() returns an object with the following fields. All values are counts.

FieldDescription
stylesIneffective style declarations removed
unwrappedAttribute-less span · font unwrapped
mergedNested or adjacent same-looking elements merged
removedEmpty formatting elements removed
brsInvisible trailing <br> removed
wrappedTop-level text runs wrapped in <p>
hoistedBlocks lifted out of <p>
zwspCaret zero-width spaces removed
totalTotal

9-M-7. Recommended setups

// New integration example — clean-up while editing (default) plus whole-body clean-up when reading
new WebEditor('#editor', { normalizeOnGet: true });

// Example for a page that needs exactly the same HTML as v2.7.0.0
new WebEditor('#editor', { autoNormalize: false });

// Example for a viewing page that does not load the content CSS — keep default font/size declarations, then save
editor.normalize({ keepDefaults: true });
const html = editor.getHTML({ normalize: false });

// Batch clean-up of stored posts example — on an admin batch page (in the browser)
for (const row of rows) {
  const html = WebEditor.normalizeHTML(row.html, { editor });
  if (html !== row.html) await save(row.id, html);
}

9-M-8. Notes

  • Differences from v2.7.0.0 — because autoNormalize is on by default, the first line typed into an empty editor is wrapped in <p> (previously bare text). After Enter, Backspace, paste or formatting a selection, the HTML has fewer spans, so the saved HTML of newly edited content differs from v2.7.0.0 (it looks the same). To keep the exact previous behaviour, set autoNormalize: false.
  • Stored content does not change until it is edited. To clean it up, use normalizeOnGet: true, or WebEditor.normalizeHTML(html, { editor }) on a batch page.
  • getHTML({ normalize: true }) and normalizeOnGet clean up without keepDefaults. If the default font and size declarations must stay, call normalize({ keepDefaults: true }) first as in the example above.
  • Automatic clean-up while editing (autoNormalize) also runs without keepDefaults. Choosing a size or font equal to the editor default (e.g. 10pt when the default is 10pt) is treated as having no effect and removed. On a page viewed without the content CSS, that text still looks the same size as the surrounding text.
  • normalize() can be reverted with a single undo (Ctrl+Z).
  • Automatic clean-up while editing does not change the element that holds the caret. For example, right after joining lines with Backspace or Delete, adjacent spans with the same formatting may remain. This keeps the "next character" formatting set at the caret; they are cleaned up on a later edit after the caret moves away, or on save (normalizeOnGet · normalize()).
  • Auto-save (autoSave) stores the content as typed, without clean-up, even when normalizeOnGet is on — so the periodic save while typing never changes the body or disturbs the undo history or the caret formatting. The sample boards (demo board and JSP board) use normalizeOnGet: true and clean up on submit.
  • The clean-up rules deal only with redundant elements on formatting tags; they do not replace security sanitising (getSafeHTML() · sanitizeOnLoad).

9-N. AI writing ai plugin v2.7.1.1

9-N-1. Overview

Use AI on selected text to refine, proofread, summarise, translate, change the tone, change the length or turn it into a table, and to get a new draft (six templates), a continuation or title suggestions. Results appear in the panel first and go into the body only when the user picks [Replace], [Insert below] or [Insert at cursor] (one undo step).

AI writing is a separate plugin outside the core. Pages that do not load it carry no AI code. The editor sends only the selected text and the task name to your server; the API key, the prompts and the model are decided by the server.

ComponentDescription
dist/plugins/ai-native.min.jsThe AI writing plugin: panel, entry points, personal-data check, result insertion, server connection (server contract v1) and a mock provider.
sdk/examples/ai-proxy-node/Server sample (Node) with Anthropic Claude (official SDK), an OpenAI-compatible gateway (in-house LLM) and optional Google translation.
JSP board /api/aiServer sample (Java 8 · Tomcat). It is wired into the board's write page, and the AI button appears only when the server has a key.
sdk/examples/ai-prompts.jsonPrompts, templates and depth (effort) per task. Both samples use the same file.
Do not put an API key in the browser. A key in the page, a bundle, the site configuration file (dee-editor.config.js) or localStorage can be read by anyone with developer tools, and the usage charges fall on your organisation. Keep the key in a server environment variable; the editor only takes ai.endpoint (your server's address).

9-N-2. Setup

Server connection example

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/ai-native.min.js"></script>
<script>
  const editor = new WebEditor('#editor', {
    plugins: WebEditor.PRESET_BUILTIN.concat(['ai']),
    ai: {
      endpoint: '/api/ai',          // your server (the key stays there)
      scope: 'allowDocument',       // with nothing selected, summary and titles use the whole document
      titleInput: '#title',         // field that [Use this title] fills
    },
  });
</script>

Example for trying the flow without a key or server (mock provider — not a real AI)

new WebEditor('#editor', { plugins: WebEditor.PRESET_BUILTIN.concat(['ai']), ai: { provider: 'mock' } });

If you define the toolbar array yourself, add 'aiOpen'. The plugin attaches itself to the menu bar [Tools], the ribbon [Tools], the right-click menu and the selection toolbar. With no server (provider) to connect to, every entry point is hidden.

9-N-3. Usage

Entry pointBehaviour
Toolbar · menu bar [Tools] · ribbon [Tools] — AI writingOpens the AI panel. Pick a task (target language, tone, length, template), add an instruction and press [Send]. What will be sent ("Sending the selected 312 characters") and the transfer notice are always shown.
Right-click (with text selected) — AI ▸Runs refine, proofread, summarise, translate or table directly.
Selection toolbar — AIOpens the panel with the selected text.
Panel footer — insert the result[Replace] · [Insert at cursor] · [Insert below] · [Copy] · [Again]. Replacing text inside one block keeps the heading, cell or list item and changes only the text. A follow-up instruction ("shorter") revises the result.

Streamed output is shown only in the panel, never typed into the body one character at a time. AI output is sanitised (WebEditor.sanitizeHTML) before insertion, and links get rel="noopener noreferrer". The panel does not open on read-only documents.

9-N-4. Option ai

ParameterDescription
endpointYour server's address (server contract v1 — 9-N-7). When set, the built-in proxy provider is used.
provider'proxy' · 'mock' · 'direct' (direct connection for development — localhost only, 9-N-9) · a name registered with registerAiProvider.
directDirect-connection settings { model, models, maxTokens, fallbacks } (9-N-9). No key is accepted here.
scope'selection' (default — selected text only) or 'allowDocument' (with nothing selected, summary and titles send the whole document and the button reads [Send whole document]).
guardPersonal-data check before sending (9-N-5). Default 'confirm'.
onGuard(items, req, { strict }) => 'send' | 'mask' | 'cancel' — confirmation for calls outside the panel (editor.ai.run).
markGeneratedWhen true, inserted blocks get a data-we-ai="task" marker (labelling generated content — it stays in the saved HTML). Default false.
titleInput · onTitleThe field (selector or element) that [Use this title] fills, or a handler (title, editor).
templatesNew-draft templates [{ id, label }]. The server picks the prompt by id. If omitted, the six defaults are used (report, notice, press release, minutes, business email, official memo).
contextCharsHow much text before the cursor a continuation sends (default 2000 characters).
stream · timeoutUse streaming (default true) · time limit (default 60000 ms).
headers · csrfCookieHeaders to add to server requests · CSRF cookie name (same convention as uploads).
onBeforeSend(req) => boolean — returning false cancels the request.
noticeReplaces the transfer notice in the panel.
mockMock provider settings { delay, chunk, fail, truncate, format } (for tests and demos).

9-N-5. Personal-data check before sending

Everything to be sent (selected text, earlier text, the previous answer, the title, the instruction and the HTML for translation) is checked with the same rules as the body's personal-data check (privacy.detect, the allow list, privacy.strict).

guardBehaviour
'confirm' (default)Shows what was found in masked form only and offers [Mask and send] · [Send anyway] · [Cancel]. Nothing is sent before the user chooses. If a never-allowed type (privacy.strict) is present, there is no [Send anyway].
'mask'Masks automatically (separators kept, letters and digits replaced with *). The result comes back masked too.
'block'Does not send if anything is found.
'warn'Sends and tells the user how many items were included.
'off'No check.
A check in the browser can be bypassed, so we recommend checking on the server as well. Both server samples refuse requests containing resident or foreigner registration numbers or card numbers with privacyCheck: 'block' (Node) or ai.privacyCheck=block (JSP board), using error code privacy. The aiGuard event and the result's guard carry only types and counts, never the values.

To apply the same rules to other text, use the core methods editor.scanSensitiveText(text) and editor.maskSensitiveText(text) (chapter 3).

9-N-6. API · events

APIDescription
editor.ai.open(action?, { run, options, prompt })Opens the panel. With run: true it sends immediately.
editor.ai.run(action, { input, prompt, options, onChunk, timeout })Runs a task and returns Promise<{ action, format, markdown, html, usage, truncated, engine, guard }>. Nothing is inserted into the body.
editor.ai.insert(result, 'replace' | 'after' | 'cursor')Inserts a result into the body (one undo step).
editor.ai.abort() · isBusy() · close()Stop · whether a request is running · close the panel.
editor.ai.available() · capabilities() · provider()Whether a provider is connected · the server's capabilities · the provider name.
editor.ai.useTitle(title)Sends one title to titleInput or onTitle.
WebEditor.registerAiProvider(adapter, { default }) · getAiProviders()Registers a provider. adapter = { name, stream(request, { signal, emit }), capabilities?() }
EventArgument
aiStart · aiChunk{ action, requestId, provider } · { action, requestId, delta, text, format }
aiDone · aiError · aiAbortedthe result · { action, requestId, code, message } · { action, requestId, text }
aiInsert · aiTitle{ mode, action, requestId } · { title }
aiGuard{ action, requestId, mode, decision, count, types } — no values
aiPanelOpen · aiPanelClose{ action } · {}

9-N-7. Server contract v1

The specification to follow if you build your own server. Both server samples follow it.

ItemDescription
RequestPOST {endpoint} · application/json — { v:1, action, input:{ selection, before, previous, documentTitle, scope, html }, prompt, options, lang, format, requestId, stream }. Text is sent as Markdown, not HTML.
Response (streaming)text/event-stream — data: {"meta":{"engine","format"}} · data: {"delta":"…"} · data: {"done":true,"usage":{…},"truncated":false} · data: {"error":{"code":"…"}}
Response (stream:false)application/json — { markdown | html, format, usage, truncated }
CapabilitiesGET {endpoint}?capabilities — { v:1, actions, templates, translate:{ engine, html, languages } }. The editor calls it once when the panel first opens.
Error codeWhat the editor tells the user
unauthorizedSign in again
rate_limitedToo many requests; try again shortly
too_largeSelect a shorter part (nothing is cut off)
refusedThe AI service did not handle the request (nothing is inserted)
privacyThe server does not accept text with personal data
upstream · timeoutTry again
disabledTurned off on the server (dimmed in the panel)

If the server sends translation to Google Cloud Translation, capabilities report translate:{ engine:'google-v3', html:true } and the editor also sends the sanitised HTML of the selection (input.html). Google translates only the text and keeps the tags, so bold, text colour and merged table cells are preserved. The instruction box is not available in this mode.

9-N-8. Server samples

SampleDescription
Node — sdk/examples/ai-proxy-nodeRun npm install, set the ANTHROPIC_API_KEY environment variable and start node server.mjs. Settings live in ai-config.json (template ai-config.sample.json); the server refuses to start if a key is written there. Run directly, it has no login check, so it listens on 127.0.0.1 only; to expose it, build a server that passes authorize (your site login check). See the sample's README.md.
JSP board — /api/aiSet the ANTHROPIC_API_KEY environment variable and start the board; the AI button appears on the write page. Settings are the ai.* keys in board.properties. See the AI writing section of the board's README.md.
Server settingDescription
Provider · modelAnthropic Claude (claude-opus-5-5) by default. The model can differ per task (for example claude-haiku-5-5 for proofreading), and an in-house LLM connects through openai-compatible with a gateway address.
Abuse protectionJSON requests only · same origin only · per-user limits per minute, per day and on concurrent requests · input limit (over it: too_large) · tasks turned off on the server · whether whole-document requests are allowed
LoggingBy default only the task, character counts, token counts and the outcome are logged — no text.

9-N-9. Direct connection for development (localhost only)

Use this on a developer PC to try the flow and the prompts with real Claude before building a server. The editor calls the Anthropic API directly from the browser.

Direct connection example

new WebEditor('#editor', { plugins: WebEditor.PRESET_BUILTIN.concat(['ai']), ai: { provider: 'direct' } });
ItemDescription
Where it worksOnly when the address is localhost, 127.0.0.1 or [::1]. On any other address (private IPs, domains, localhost.example.com and so on) the provider counts as missing, every entry point is hidden and the console notes it once.
KeyNot accepted as an option. Typed into the field at the top of the panel, it is stored only in this tab's sessionStorage and is gone when the tab closes. The field never shows the saved key again; [Clear] removes it.
PromptsThe same prompts as the server samples (a copy of ai-prompts.json). The personal-data check (ai.guard) applies as usual.
Setting ai.directmodel (default claude-opus-5-5) · models (per task) · maxTokens (default 4000) · fallbacks ('auto')
TranslationClaude translates (the Google translation engine is available only through a server).
Do not use it on production pages. In production, go through your server (ai.endpoint) so the key never reaches the browser. For development, we recommend a separate key with a low spending limit.

9-N-10. Settings reference

AI writing settings live in the five places below. The API key goes only in a server environment variable.

WhereWhat it decides
Page option aiServer address (endpoint) · whole-document requests (scope) · personal-data check (guard) · generated-content marker · title field · template list (9-N-4)
Server settings fileProvider · model · enabled tasks · limits · rate limits · server-side personal-data check · translation engine · logging — ai-config.json for Node, the ai.* keys in board.properties for the JSP board
Prompt file ai-prompts.jsonPer-task instructions · tone · length · target languages · template instructions · depth (effort)
Server environment variablesAPI keys (ANTHROPIC_API_KEY · GOOGLE_TRANSLATE_API_KEY · GOOGLE_APPLICATION_CREDENTIALS)
Site configuration file (dee-editor.config.js) v2.7.1.1Public values for the whole site — server path · tasks to use · personal-data check · what is sent · generated-content marker · templates · notice (see "ai in the site configuration file" below). It takes no keys.

Where to put the API key

EnvironmentSetting
Node sampleAn environment variable in the shell that runs it — set ANTHROPIC_API_KEY=<key> (Windows) · export ANTHROPIC_API_KEY=<key> (Linux), then node server.mjs. Rename it with apiKeyEnv.
JSP board — Windows packageSystem environment variable ANTHROPIC_API_KEY (Control Panel → System → Advanced → Environment Variables), then restart the board
JSP board — Ubuntu packageexport ANTHROPIC_API_KEY=<key> in conf/board.env, then ./board.sh restart (export is needed for Java to see it)
JSP board — Linux (Tomcat 7) packageAn environment variable for the account that runs Tomcat (for example export ANTHROPIC_API_KEY=<key> in setenv.sh), then restart Tomcat
If it must be in a file (JSP)Only ai.apiKey=<key> in board-local.properties, which is kept out of commits and packages. Never in board.properties.

The JSP board looks for the key in this order: ai.apiKey (environment variable AI_APIKEY → system property → board.conf → board-local.properties), then the environment variable named by ai.apiKeyEnv (default ANTHROPIC_API_KEY). Without a key, AI is off and the write page shows no button.

Node sample — ai-config.json

ParameterDescription
provider'anthropic' (default) · 'openai-compatible' (in-house LLM — requires baseUrl)
model · modelsDefault model (claude-opus-5-5) · per-task models (for example { "proofread": "claude-haiku-5-5" })
apiKeyEnvName of the environment variable holding the key (default ANTHROPIC_API_KEY). The server refuses to start if a key value (apiKey) is written in the file.
baseUrlIn-house gateway or proxy address
fallbacks'auto' (default — server-side fallback on Opus, Fable and Sonnet) · true · false
path · port · host'/api/ai' · 3400 · '127.0.0.1' (the AI_PORT environment variable wins if set)
maxInputChars · maxOutputTokens · maxBodyBytes · maxHtmlChars8000 · 4000 · 262144 · 30000 — over the limit returns 413 too_large (nothing is cut off)
rateLimit{ "perMinute": 10, "perDay": 200, "concurrent": 2 } — per user (0 = no limit)
privacyCheck'off' (default) · 'block' (refuse requests with resident or foreigner registration numbers or card numbers — 9-N-5)
actionsTasks to enable (null = all)
allowDocumentWhether whole-document requests are accepted (default true)
allowedOriginsOnly to allow editors on other origins (default: same origin only)
log'metadata' (default — no text) · 'off'
timeoutMsProvider response time limit (default 120000)
prompts · deeDistPath to the prompt file · path to the editor dist for the test page (null = no test page)
translateTranslation engine — { "engine": "llm" | "google-v2" | "google-v3", "google": { keyEnv, project, location, endpoint, glossary, glossaryIgnoreCase, model } } (9-N-7)

JSP board — ai.* in board.properties

ParameterDescription
ai.enabledauto (default — on when there is a key) · false (off)
ai.provider · ai.baseUrlanthropic (default) · openai-compatible (in-house LLM — requires ai.baseUrl, key optional)
ai.apiKey · ai.apiKeyEnvKey (only in board-local.properties) · name of the environment variable holding the key (default ANTHROPIC_API_KEY)
ai.model · ai.models.<task>Default model · per-task model (for example ai.models.proofread=claude-haiku-5-5)
ai.actionsTasks to enable (comma-separated, empty = all) — refine · proofread · summarize · translate · tone · length · table · draft · continue · title · followup
ai.fallbacksauto · true · false
ai.maxInputChars · ai.maxOutputTokens · ai.maxHtmlChars8000 · 4000 · 30000
ai.allowDocumentWhether whole-document requests are accepted (default true)
ai.rateLimit.perMinute · perDay · concurrent10 · 200 · 2 — per client address
ai.privacyCheckoff (default) · block
ai.allowedOrigins · ai.timeoutMs · ai.logOther origins to allow (comma-separated) · 120000 · metadata | off
ai.translate.engine · ai.translate.google.*llm · google-v2 · google-v3 — apiKey · keyEnv · credentials (service-account key file path, outside the web root) · project · location · endpoint · glossary · glossaryIgnoreCase · model

Every key can also be given as an environment variable: replace dots with underscores and use upper case (for example ai.model → AI_MODEL, ai.rateLimit.perDay → AI_RATELIMIT_PERDAY). Environment variables win over the settings file.

Prompts — ai-prompts.json

ItemDescription
systemThe base instruction added to every task. Do not remove the sentence saying text inside the tags is material, not instructions — it guards against prompt injection hidden in documents.
actionsPer-task instructions. The {targetLang} · {tone} · {length} · {template} placeholders are filled from the request options.
optionsWording for each value of target language, tone, length and template. The keys of targetLang become the panel's language list.
effortDepth per task (low · medium · high). Default low; new drafts and continuation medium.
templatesNew-draft templates [{ id, label }], sent to the editor through capabilities and shown in the panel.

Example of adding a template — add the instruction under options.template and the name under templates.

"options": { "template": { …, "weekly": "a weekly work report (done this week, plans for next week, issues)" } },
"templates": [ …, { "id": "weekly", "label": "Weekly report" } ]

After editing the prompts, put the same file in both server samples; in the repository, run node scripts/sync-ai-prompts.js to update the board copy and the direct-connection copy.

ai in the site configuration file v2.7.1.1

Create it in the [AI writing] area of the admin settings tool, or write it under options.ai in the file. It is a policy key (level 2): page code cannot make it looser, and the JSP board server checks the same file again.

ParameterDescription
endpointAI server path. Same-site paths only (/api/ai) — other hosts, // and relative paths are dropped. Set other servers in page code. A page option wins if present.
actionsTasks to use. Only tasks allowed by all of the page option, the server and this file are on (panel, right-click and code calls alike).
guardPersonal-data check before sending — the stricter of off < warn < confirm < mask < block applies. With block or mask, the JSP board server also refuses requests containing personal data.
scopeWith selection, only the selected text is sent even if the page sets allowDocument (the server also refuses whole-document requests).
markGeneratedWith true, AI-written parts are marked even if the page sets false.
templates · noticeNew-draft templates [{ id, label }] · transfer notice — display values, so a page option wins if present.
Not acceptedSub-keys that carry secrets, such as keys, headers or cookies (apiKey, headers, token … — forbidden), and code values such as provider or direct (unknown) are dropped with one console notice.

Site configuration file example

window.DEEDITOR_CONFIG = { "$schema": "dee-editor-config", "version": 1, "options": {
  "ai": { "endpoint": "/api/ai", "guard": "block", "scope": "selection", "markGenerated": true,
          "actions": ["refine", "proofread", "summarize", "translate"],
          "templates": [{ "id": "report", "label": "Report" }, { "id": "notice", "label": "Notice" }] }
} };

Recommended settings example — public-sector and financial organisations

SettingValue
Editor ai.guard'block' or 'mask' — text with personal data is not sent, or is sent masked.
Editor privacy.strict['ssn', 'bank-account', 'credit-card'] — removes [Send anyway] from the confirm box.
Editor ai.scope · server allowDocument'selection' · false — only the selected text is sent.
Editor ai.markGeneratedtrue — marks AI-written parts in the saved HTML.
Server privacyCheck'block' — the server also refuses requests that bypassed the browser check.
Server providerOn closed networks openai-compatible (in-house LLM); to pin the data location, google-v3 for translation with the translate-eu or translate-us endpoint
Server log'metadata' — usage only, no text.
AI usage is billed under your organisation's contract with the provider (Anthropic, Google and so on). Check the provider's data-retention and processing-region settings before signing. Public-sector and financial organisations should first check their internal policy on sending text to external services; on closed networks, use an in-house LLM (openai-compatible).

9-O. Charts chart plugin v2.7.3.0

9-O-1. Overview

Type values into the data grid, or paste a range from Excel, to insert column, bar, stacked bar, line, area, pie and doughnut charts into the document. You can also right-click a table in the document and choose [Create chart from this table].

Charts are a separate plugin, kept apart from the core. The saved HTML is inline SVG inside figure.we-chart plus the data (data-we-chart, JSON), so viewing pages, print and PDF export show the chart without the plugin. The editing view does not trust the saved SVG; it redraws the chart from the data. Many mail services (Gmail and others) strip SVG from the message body, so for email insert the picture saved with the chart's [Save as image (PNG)] menu, or use output:'image' (9-O-8).

PartDescription
dist/plugins/chart-native.min.jsThe chart plugin: renderer (SVG), model validation, insert dialog, data grid, charts in the document (select, resize, align), table ↔ chart and the entry points.
dist/webeditor-content.cssContent CSS for viewing pages. It contains the rule that shrinks charts to fit narrow columns (the chart's look is self-contained in the SVG).
demo/en/chart.htmlChart demo. Shows the saved HTML and the viewing page side by side.

9-O-2. Setup

Setup example

<script src="dist/webeditor.min.js"></script>
<script src="dist/plugins/chart-native.min.js"></script>
<script>
  const editor = new WebEditor('#editor', {
    plugins: WebEditor.PRESET_BUILTIN.concat(['chart']),
    chart: { defaultType: 'column', palette: ['#1F4E79', '#F28E2B', '#59A14F'] },   // optional — 9-O-7
  });
</script>

Viewing page example (no plugin)

<link rel="stylesheet" href="dist/webeditor-content.css">
<div class="we-content"><!-- saved body HTML --></div>

Pages that define their own toolbar array add 'insertChart'. The plugin adds itself to the menu bar [Insert ▸ Chart…], the ribbon [Insert] tab and the context menu automatically.

9-O-3. Usage

Entry pointBehaviour
Toolbar · menu bar [Insert ▸ Chart…] · ribbon [Insert] — ChartOpens the insert dialog. A new chart starts with sample data (4 categories × 2 series) so the preview shows at once. With a chart selected, it opens that chart's edit dialog.
Right-click a table — Create chart from this tableOpens the dialog with the table's data. [Insert] puts the chart right below the table (9-O-6).
Click · double-click a chartClick selects it (border, handles, toolbar); double-click opens the edit dialog (9-O-5).
Right-click a chartEdit chart · Change chart type ▸ · Align ▸ · Reload from table (charts made from a table only) · Convert to table · Save data as CSV · Save as image (PNG) · Delete chart

In read-only documents none of the entry points open, and charts stay visible.

9-O-4. Insert dialog · data entry

The dialog has 8 type buttons, the data grid, a live preview and appearance settings (title, legend, category axis title, value axis title, number format, colours, size, data labels). In the grid the first row holds series names, the first column category names, and the top-left cell the category axis title (the same value as the [Category axis title] field). Drag the window header to move the window (double-click to re-center), or fold it with the ▴ button to see the document while entering values. Choosing pie or doughnut turns data labels on, and a note under the preview says negative items are not drawn.

The notation in value cells becomes the number format — 9.0 gives 0.0, 12% a percentage. When an amount column and a % column are mixed, the value axis follows the first series' format as in Excel, and the data grid, data labels and CSV keep the notation entered for each series (series[].format). There is only one value axis, so a note under the preview says a series with different units does not match the ticks. A format picked from the cell notation returns to General when you paste values without that notation (a format you chose yourself stays).

Vertical axis titles (the category axis of a bar chart, the value axis of a column chart) start at the top. Titles of up to 8 characters are stacked one character per line whatever the script (구분 · Q1 · 2026년); longer titles and English words (Revenue) are turned to read top to bottom. CSV keeps the cell notation (9.0), but Excel drops formatting when it opens a CSV and shows 9.

FeatureDescription
MovingArrows · Tab/Shift+Tab · Enter/Shift+Enter · Home/End · Ctrl+arrows · Ctrl+Home/End
EditingPick a cell and type (IME composition included) · F2 or double-click to edit the current value · Delete to clear · Esc to cancel · Ctrl+Z/Y (grid-only undo)
Rows · columns[Add row] · [Add column], or right-click a cell (or Shift+F10) — insert row above/below · delete row · insert column left/right · delete column
PasteCtrl+V a range copied from Excel, Hangul or Google Sheets — the clipboard table (HTML) is read first, otherwise tab-separated text (the comma in 1,250 does not split cells). When pasting into the top-left cell and the first row or column is not text, the data goes into the value cells and the name cells are left alone. A table with a header row and column pasted into the top-left cell replaces the whole grid, and merged multi-row headers (Q3 results over Sales · Cost) become one row as in Excel (Q3 results Sales).
CSV[Load CSV] or drop a file onto the grid — UTF-8 and CP949 (EUC-KR) are detected automatically; quotes, commas and line breaks inside cells follow CSV rules.
Reading numbers1,250 · 12.5% · ₩1,000 · 1,000원 · (120) (negative) · −5. An empty cell is an empty value, not 0 (no bar, a gap in the line). The number format follows how cells are written (commas, decimals, %, currency) until you pick a format yourself.
Invalid cellsValue cells that are not numbers get a red border and [Insert] is disabled.
Swap rows ⇄ columnsSwaps series and categories.

Pie and doughnut charts draw only the first series; with more than one series a note appears under the preview. The limits are 200 categories, 12 series and 2,000 value cells; a paste or CSV that goes beyond them is cut and you are told.

9-O-5. Charts in the document

ActionDescription
SelectClicking a chart shows a border, 4 corner handles and a toolbar ([Edit] [Align left · centre · right] [Delete]). All of these live in a layer outside the body, so they never end up in the saved HTML.
ResizeDragging a handle resizes the chart keeping its ratio (from 160px up to the body width). On release the chart is redrawn at the new size, so text keeps its size.
AlignStored as the figure's margin; it survives resizing and reloading.
MoveDrag a chart; a line shows where it will drop between paragraphs.
KeyboardWith a chart selected: Delete/Backspace (delete) · Esc (deselect) · Enter (edit dialog) · arrows (to the previous/next paragraph — an empty one is created if there is none). Delete and Ctrl+Z work after selecting a chart even when focus is outside the body (for example on a toolbar button).
Copy · pasteCharts are copied with their data, so they stay editable when pasted into another Dee Editor. Pasted charts are redrawn from the data, so anything slipped into the saved SVG is dropped. Other programs receive the data as a tab-separated table.
UndoInsert, edit, resize, align, move, delete and paste are one step each.

Text inside charts (title, series names, ticks) is excluded from find & replace and from the character count. To change it, edit the data in the dialog.

9-O-6. Table ↔ chart

FeatureDescription
Create chart from this tableAdded at the end of the table context menu. Columns where at least half the cells below the first row are numbers become series; the first column that is not a series becomes the categories; other text columns (notes and so on) are dropped. Merged cells count as having their value in the first cell, and year header rows (2025 · 2026) and year category columns are read as names. Merged multi-row headers become one row, and a wide table with more value columns than value rows (January … December across) is read with rows as series, as in Excel. Cells that cannot be read as numbers are left empty and the dialog says how many. Greyed out for tables with no numeric column.
Link[Insert] marks the table with data-we-chart-src and the chart data with the same source. Cancelling the dialog leaves the table untouched. Insert and marking are one undo step.
Dialog → source table v2.7.3.0When you edit a chart made from a table and press [Update], the edited values, category names and series names are written back to the source table. The insert dialog opened by [Create chart from this table] works the same way: edit the data there and [Insert] puts the chart in and updates the table cells. The dialog says so below the data grid. The table is not rebuilt — only cell text changes — so its look (borders, background, bold, column widths) and the columns the chart does not read (notes and so on) stay as they are. Cells whose value did not change are left alone, and changed cells keep the notation that cell used (thousands separators, %, currency). Cells that could not be read as numbers (N/A, - and so on) are left as they are unless you enter a value in the dialog. If categories or series are added, rows and value columns are added after the last ones in the same style; if they are removed, they are deleted from the end. A table with merged cells cannot be resized, so in that case only the chart changes and a notice appears. The chart and the table (and, on insert, the link mark) are one undo step. Turn it off with chart.syncTable: false.
Reload from tableOnly on charts made from a table. Redraws from the table's current values, keeping the type, appearance and colours. Greyed out if the table is gone.
Convert to tableReplaces the chart with a table in the same place; values are written in the chart's number format.

9-O-7. Option chart · site configuration

ParameterDescription
syncTable v2.7.3.0Whether editing a chart made from a table (in the edit or insert dialog) also updates the source table. Default true (9-O-6).
svgMissingNoticeWhether to show an editor notice bar when charts in loaded content have had their SVG removed. Default true. The event and console warning are not turned off (9-O-8).
output'svg' (default) or 'image'. 'image' is for sites whose server XSS filter strips SVG (9-O-8).
defaultTypeType for new charts: 'column' (default) · 'bar' · 'columnStacked' · 'barStacked' · 'line' · 'area' · 'pie' · 'doughnut'
paletteColours for new charts: a name ('default' · 'office' · 'mono' · 'pastel') or an array of brand colours #RRGGBB (up to 12, used in series order). The dialog shows it as [Custom colours].

In the site configuration file (dee-editor.config.js, 2-2-1), chart is level 2 (policy). When the site sets output: 'image', page code cannot switch back to 'svg'; the default type and colours can be overridden by the page. Other sub-keys are dropped. disablePlugins: ['chart'] turns charts off, and the admin settings tool has a [Charts] panel for choosing brand colours with a preview.

Site configuration example

window.DEEDITOR_CONFIG = {
  $schema: 'dee-editor-config', version: 1,
  options: { chart: { defaultType: 'line', palette: ['#1F4E79', '#F28E2B', '#59A14F'] } },
};

9-O-8. Saved format · viewing pages · server filters

Saved format example

<figure class="we-chart" data-we-chart="{&quot;v&quot;:1,&quot;type&quot;:&quot;column&quot;,…}"
        style="width:600px;max-width:100%;margin:12px auto;position:relative;z-index:0;line-height:0;aspect-ratio:600 / 320">
  <svg class="we-chart-svg" viewBox="0 0 600 320" width="600" height="320" role="img" aria-label="Q3 results">…</svg>
  <div class="we-chart-alt" style="position:absolute;…;z-index:-1;…">📊 Chart 'Q3 results' — this page cannot display the chart image (SVG). Jul Sales 12.4, Cost 8.1 · …</div>
</figure>
ItemDescription
SVG elements · attributesOnly the same elements as the shapes feature — svg g rect line path polygon text tspan. All text is escaped and colours are #RRGGBB only. Customer server filters (jsoup, Lucy, OWASP) should allow these elements, the attributes xmlns class viewBox width height role aria-label font-family x y x1 y1 x2 y2 d points fill stroke stroke-width transform font-size font-weight text-anchor, and the outer figure with class · style and data-we-chart.
data-we-chartThe chart data (JSON). The editing view redraws from it; if it cannot be read (hand-edited, over the limits) the saved SVG is kept as is. It falls under data-we-* in the filter allow list.
contenteditableAn editing-time attribute, so it is removed from getHTML() output; the plugin sets it again on load.
Fallback text div.we-chart-altText for mail services and server filters that strip SVG. It holds the chart title, a notice and a data summary (up to 300 characters, in each series' notation), and sits behind the SVG with inline styles (z-index:-1), so the SVG covers it. If the SVG is removed, this text shows in the chart's place (the box's aspect-ratio keeps its height). Mail that also strips position (Gmail and others) shows it as a plain text box. Allow div and the style properties position · z-index · aspect-ratio in your filter — a filter that keeps the SVG but strips only these styles shows the text under the picture as well.
Charts that come back without SVGIf loaded HTML has the data (data-we-chart) but no SVG or picture, the chart is redrawn from the data and reported through the chartSvgMissing event ({ count, els }), a developer console warning and an editor notice bar. Turn the notice bar off with chart: { svgMissingNotice: false }. If you see it, your server filter strips SVG — consider image mode (output: 'image').
Image mode output: 'image'For sites whose server filter removes SVG altogether. After insert, edit or resize, a PNG is uploaded through uploadHandler and the figure's content becomes <img src alt width height style> (in the same undo step as the insert). The filter then only needs figure and data-we-chart. Without uploadHandler charts are saved as SVG. Images are less sharp than SVG in print and when zoomed.
In image mode, wait for uploads with await editor.chart.whenReady() before saving. If getHTML() runs before an upload finishes, that chart is saved as SVG. If an upload fails, or the returned address is not http(s), a same-site path or data:image/png|jpeg, the chart stays SVG and chartImageError fires.

Image mode save example

async function save() {
  await editor.chart.whenReady();          // until every chart image is uploaded
  const html = editor.getSafeHTML();
  await fetch('/board/save', { method: 'POST', body: html });
}

9-O-9. API editor.chart

MethodDescription
open(model? | figure, { mode, ref })Opens the insert dialog; with a figure, that chart's edit dialog. Returns false when read-only, already open, the chart data cannot be read, or the key is a Basic Pack subscription key (6-2-1).
insert(model, { mode, ref })Inserts without the dialog. mode is 'cursor' (default) · 'end' · 'after' (after the ref paragraph). Returns the inserted figure, or null (also with a Basic Pack subscription key). If the model would draw differently from what was meant (data instead of values · non-numeric values · all values empty · unknown type and so on) it logs one warning line to the developer console.
get(el) · update(el, model)Reads (a copy of) and replaces a chart's model. update returns { ok, errors, warnings }; warnings holds the same sentences as the console warning.
list() · refresh(root?)Lists the charts in the document · redraws from data (returns the number changed). Runs automatically after setHTML, appendHTML and insertHTML.
select(el) · selected() · deselect()Chart selection.
align(el, 'left' | 'center' | 'right') · resize(el, width) · remove(el)Align · resize (keeps the ratio) · delete. One undo step each.
fromTable(table) · openFromTable(table)Table → model · the same as [Create chart from this table].
reload(el) · toTable(el)The same as [Reload from table] · [Convert to table].
writeTable(el)Writes the chart data to the source table (the same rules as [Update] in the dialog, one undo step). Returns true if the table changed, false if there is no source table or nothing to change.
toCsv(el) · toPng(el, { scale }) · download(el, 'csv' | 'png')CSV text (cells starting with = get a leading ' so spreadsheets do not run them as formulas) · PNG Blob (white background, 2× by default, scale 1–4) · download as a file named after the chart title.
isOpen() · close()Whether the insert dialog is open · closes it (same as Cancel; chartClose reports result: 'cancel').
render(model, opts) · figureHTML(model)Same as WebEditor.renderChart · chartFigureHTML below, using this editor's font.
versionThe chart extension's version string.
whenReady()A Promise that resolves when every image-mode upload has finished.
WebEditor.renderChart(model, { font, ariaLabel })Model → SVG text { svg, model, errors, warnings } without an editor (viewing pages, server previews, reports). It does not write to the console.
WebEditor.chartFigureHTML(model, { align, language, font })Builds the saved-format figure HTML without an editor (empty string if validation fails). align is 'left' · 'center' (default) · 'right'; language: 'en' writes the fallback text in English.

9-O-10. Events

EventDescription
chartInsert · chartUpdate{ el, model } — after insert · update
chartTableSync{ el, table } — after the chart data is written to the source table ([Update] in the edit dialog · [Insert] in a dialog opened from a table · writeTable).
chartRemove{ model, reason } — after delete · convert to table. Converting to a table also sends reason: 'toTable' and the new table.
chartOpen · chartClose{ edit, el } · { result: 'insert' | 'update' | 'cancel', el } — insert dialog
chartImage · chartImageError{ el, url } · { el, error } — image-mode upload result
chartSvgMissing{ count, els } — charts in loaded HTML had no SVG (removed by a server filter or service) and were redrawn from their data

9-O-11. Data model

Data model example

{
  v: 1,
  type: 'column',                 // column · bar · line · area · pie · doughnut
  stacked: false,                 // bar and area only
  title: 'Q3 results',
  labels: ['Jul', 'Aug', 'Sep'],
  series: [
    { name: 'Revenue', values: [12.4, 13.9, 15.2] },
    { name: 'Cost', values: [8.1, null, 9.0], color: '#ED7D31' },   // null = empty value
    // { name: 'Margin', values: [0.12, 0.15, 0.2], format: '0%' }   // format: notation of a series with different units (optional)
  ],
  options: {
    legend: 'auto',               // auto · top · bottom · right · none
    dataLabels: false,
    valueAxis: { title: '$M', min: null, max: null, format: '#,##0.0' },
    categoryAxis: { title: '' },
    palette: 'default',           // a name or an array of #RRGGBB
    hole: 50,                     // doughnut hole (%)
  },
  size: { w: 600, h: 320 },       // 160–1600 × 120–1200
  source: null,                   // the table's data-we-chart-src when made from a table
}

The model is validated on every insert, update and load. Only values that pass the type, limits (200 categories · 12 series · 2,000 value cells · 32KB of JSON), colour (#RRGGBB), number format (a subset of Excel formats such as #,##0 · 0.0% · #,##0"원") and text length checks are drawn.

10-A. Multilingual (i18n) support

The entire editor UI — menu bar, ribbon, toolbar tooltips, every plugin dialog, and the import dialogs — follows the language option. ko and en are included in the core, and WebEditor.registerLocale() lets you add a language or override individual strings.

Backwards compatible: if you leave language unset, it stays 'ko'. Existing code renders exactly as before. Automatic detection requires an explicit 'auto'. This opt-in policy ensures that users on an English OS do not suddenly see an English UI.

10-A-1. Choosing a language

// start with the English UI
const editor = new WebEditor('#editor', { language: 'en' });

// detect from the environment — <html lang> then navigator.language; falls back to ko
new WebEditor('#editor', { language: 'auto' });
ValueBehaviour
'ko' (default)Uses Korean. This is the same as leaving the option out.
'en'Uses English, which is built into the core.
'auto'Detects the language from <html lang>, then from navigator.language. If none is registered, it falls back to 'ko'.
'ja'Uses Japanese, which is not built into the core. Make sure to load dist/locales/ja.js alongside it. Refer to 10-A-4.
anything elseUses a code registered first with registerLocale(). Unregistered codes fall back to 'ko'.

10-A-2. Runtime switching — setLanguage()

setLanguage(lang) → this

Switches the UI language immediately. The body HTML, caret, modified flag, and read-only state are preserved, and any open popups or dialogs are closed. The languagechange event fires when it finishes. Unregistered codes are ignored and reported through the 'error' event and the onError option (context 'setLanguage').

editor.on('languagechange', (lang) => {
  console.log('switched to:', lang);
});

editor.setLanguage('en');
editor.getLanguage();   // 'en'
How it works: a toolbar button's title receives an already-resolved string at registration time, so no key survives in the DOM. That is why the body (.we-body) is left alone while only the chrome — menu bar, ribbon, toolbar, and plugins — is destroyed and rebuilt. Switching is per instance, so to switch several editors, call it on each one.

10-A-3. Adding a language or overriding strings — registerLocale()

WebEditor.registerLocale(name, pack, opts?) → boolean

A locale pack is a flat map of 'namespace.key' → string. {name} placeholders inside the values are substituted at runtime. Make sure to call it before you create the editor.

// ① register a new language — missing keys fall back to ko, so partial packs are safe
WebEditor.registerLocale('ja', {
  'menu.file': 'ファイル',
  'menu.edit': '編集',
  'core.placeholder': '内容を入力してください。',
});
new WebEditor('#editor', { language: 'ja' });

// ② override just a few strings in an existing pack (merge)
WebEditor.registerLocale('en', {
  'menu.file': 'Document',
}, { merge: true });
If you leave out merge: true, the pack is replaced entirely, so every key you did not specify falls back to ko. Please always enable merge when changing only some strings.

10-A-4. The Japanese pack (included)

Japanese is not built into the core. Only ko and en are included in the bundle, so that no one has to load a language they do not use; every other language is provided as a separate dist/locales/<code>.js. Loading ja.js calls registerLocale('ja', …) automatically.

<!-- the core and the language pack — the order does not matter -->
<script src="dist/webeditor.min.js"></script>
<script src="dist/locales/ja.min.js"></script>

const editor = new WebEditor('#editor', { language: 'ja' });
ItemDetail
FilesThe files are dist/locales/ja.js (readable) and dist/locales/ja.min.js (production, about 46 KB).
KeysThere are 832 keys: 660 core keys, 139 for the import add-ons and 33 for the text recognition add-on. They cover menus, toolbar, every dialog, and the import flow.
Load orderThe scripts can be loaded in any order. The import bundles merge only into ko and en, so they never conflict with ja.
Changing wordingThere is no need to edit the language pack file. Simply override the keys you want to change with WebEditor.registerLocale('ja', { key: 'text' }, { merge: true }) (10-A-3).
Globalwindow.DeeEditorLocaleJA exposes the pack object.
A missing key shows up in Korean. The fallback chain is “requested language → ko → [key]”. The bundled pack includes all 832 keys (it is checked against the core dictionary for missing keys before each release). When you override wording yourself, please always pass { merge: true }; without it, the whole pack is replaced and everything you did not list falls back to Korean.
The trial modal is available in Japanese too (licenseLang: 'ja'). The licence module can appear before the editor is created, so it has its own separate dictionary. If the option is unset, it detects the language from <html lang>.
A working example is included in the Japanese package as demo/index.html (with runtime language switching); it is not part of this English distribution. For Japanese customers, dee-editor-v2.7.4.0-ja.zip is available, containing the language pack, one worked example, and a Japanese quick-start.

10-A-5. Key namespaces

There are currently 832 keys each for ko, en and ja. You can find the full key list in the Japanese pack dist/locales/ja.js (unminified), which contains the keys of the core and of the import extension packs.

NamespaceScope
menu.*Menu bar items
rb.*Covers ribbon card labels (including line breaks).
tb.* · it.* · sv.*Shared toolbar · inline toolbar · source-view tabs
fmt.* · table.* · shape.* · ins.* · img.* · link.* · find.* · video.* · emoji.* · docbg.*Plugin tooltips and dialogs
guard.*Content & privacy check
core.* · msg.* · about.* · a11y.*Core messages · notices · About dialog · accessibility labels
imp.*Covers the import extension packs (Word · HWPX · XLSX · PPTX · Markdown).
imp.* is stored not in the core dictionary but inside each extension bundle, which merges it in on load with registerLocale(…, { merge: true }). Projects that do not use the extensions never load those strings. To override an imp.* string, please call it after loading the extension script.

10-A-6. Out of scope

ItemNotes
Body contentContent that the user types or imports is not translated.
Date/time insert formatsThe format list in insertDateTime is currently designed for Korean (there are no per-language default formats).
Trial modalThe trial modal follows the separate licenseLang option ('ko' · 'en' · 'ja'). Its dictionary is separate from the core.
Demo and manual pagesThe pages themselves are separate documents. The English set is demo/en/; the Japanese worked example is demo/ja/.
Font listEntries in the font drop-down are real font names, so they read the same in every language.

11. TypeScript type definitions

The full set of types is available in dist/webeditor.d.ts.

interface WebEditorOptions {
  height?: string | number;
  width?: string | number;
  placeholder?: string;
  defaultFont?: string;
  defaultFontSize?: number;
  defaultLineHeight?: string | number;
  language?: 'ko' | 'en' | 'auto' | string;
  toolbarOverflow?: boolean;
  contentCSS?: string;
  readOnly?: boolean;
  autofocus?: boolean;
  enterKey?: 'p' | 'br';
  undoGranularity?: 'char' | 'group';
  undoMaxBytes?: number;
  documentBackground?: { mode?: 'auto' | 'base64' | 'upload'; inlineThreshold?: number; store?: 'auto' | 'wrapper' | 'meta'; onTooLargeWithoutUploader?: 'fallback' | 'block' };
  uiTemplate?: 'classic' | 'ribbon';
  iconTheme?: string;
  iconThemePath?: string;
  maxImageWidth?: number;              // caps the displayed size (CSS) only
  imageResize?: {                      // downscales the actual pixels
    maxWidth?: number;
    maxHeight?: number;
    quality?: number;
    formats?: string[];
    onLargerResult?: 'original' | 'resized';
  } | null;
  pastePlainText?: boolean;
  showTableGuide?: boolean;
  logoUrl?: string;
  license?: string;
  licenseLang?: 'ko' | 'en' | null;
  uploadHandler?: (file: File, headers?: Record<string, string>) => Promise<string>;
  onError?: (context: string, error: Error) => void;
  plugins?: string[] | Record<string, PluginClass>;
  menubar?: boolean | MenuBarGroup[];
  onInit?: (editor: WebEditor) => void;
  onKeyDown?: (e: KeyboardEvent) => boolean | void;
  onKeyUp?: (e: KeyboardEvent) => void;
  onBeforeCommand?: (cmd: string) => boolean | void;
  onTabChange?: (index: number) => boolean | void;
  onMenuCommand?: (cmd: string, editor: WebEditor, item: any) => boolean | void;
  onLicenseValid?: (info: LicenseInfo) => void;
  onLicenseInvalid?: (state: LicenseState) => void;
  storageInfo?: boolean | null;   // v2.6.8 — Browser storage window (default: editors with autoSave on)
  autoSave?: { interval?: number; storageKey?: string; scope?: string | ((editor: WebEditor) => string); unloadWarning?: boolean; unloadMessage?: string; onSave?: (html: string) => boolean | void; storage?: 'localStorage' | 'indexedDB' | { get, set, remove } } | null;
  inlineToolbar?: boolean | string[];
  hyperLinkDefaultTarget?: '_self' | '_blank' | '_top' | '_parent';
  privacy?: { detect?: string[]; onDetect?: (m: any[]) => void } | null;
  profanity?: { words?: string[] | string; onDetect?: (m: any[]) => void; maskChar?: string } | null;
  // when words is omitted, window.WebEditorBannedWords (array | file URL) is used
  uploadHeaders?: Record<string, string> | null;
  csrfCookie?: string | null;
  evaluationWatermark?: boolean;
  autoNormalize?: boolean;    // v2.7.1.0 — automatic tag clean-up while editing (default true)
  normalizeOnGet?: boolean;   // v2.7.1.0 — clean up before getHTML() · getSafeHTML() return (default false)
}

interface WebEditorNormalizeOptions { structure?: boolean; keepDefaults?: boolean }   // v2.7.1.0
interface WebEditorNormalizeReport { styles: number; unwrapped: number; merged: number; removed: number; brs: number; wrapped: number; hoisted: number; zwsp: number; total: number }

interface LicenseInfo {
  valid: boolean;
  domains: string[];
  expiry: number;  // UNIX timestamp (0 = perpetual)
  type: 'perm' | 'year' | 'trial30' | 'trial180' | 'custom';
  customer: string | null;
}

interface DocumentBackground {
  image: string | null;   // a data URL or an uploaded URL
  color: string;          // '' = no color
  repeat: 'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat';
  attachment: 'scroll' | 'fixed';
  mode: 'base64' | 'upload' | null;  // how the image was actually handled
  store: 'wrapper' | 'meta';      // where the background is preserved
}

declare class WebEditor {
  static version: string;
  static registerPlugin(name: string, plugin: PluginClass): void;
  static getAPIModelById(id: string): WebEditor | null;
  static getAPIModelByIndex(index: number): WebEditor | null;
  static getAllAPIModels(): WebEditor[];
  static normalizeHTML(html: string, options?: WebEditorNormalizeOptions & { editor?: WebEditor }): string;   // v2.7.1.0

  constructor(selector: string | Element, options?: WebEditorOptions);

  getHTML(options?: { normalize?: boolean; structure?: boolean }): string;
  normalize(options?: WebEditorNormalizeOptions): WebEditorNormalizeReport;   // v2.7.1.0
  setHTML(html: string): this;
  getText(): string;
  appendHTML(html: string): this;
  insertHTML(html: string): this;
  getSelectedHTML(): string;
  getSelectedText(): string;
  clear(): this;
  setReadOnly(readonly: boolean): this;
  isReadOnly(): boolean;
  isModified(): boolean;
  resetModified(): this;
  setHeight(height: number | string): this;
  setFixedHeight(on: boolean): this;
  getHeight(): number;
  setWidth(width: number | string): this;
  getWidth(): number;
  setTab(n: 0 | 1 | 2 | 'edit' | 'html' | 'preview'): this;
  getActiveTab(asName?: boolean): 0 | 1 | 2 | 'edit' | 'html' | 'preview';
  showToolbar(visible: boolean): this;
  insertImage(url: string, alt?: string): this;
  getImages(): string[];
  getDeletedImages(prefix?: string): string[];   // v2.6.8
  clearFormat(): this;
  clearCSSFormat(): this;
  removeTag(tagName: string): this;
  setDefaultFont(name: string): this;
  setDefaultFontSize(size: number): this;
  setDefaultLineHeight(lh: string | number): this;
  setEditorDefaults(opts: { font?: string; fontSize?: number; lineHeight?: string | number }): this;
  getEditorDefaults(): { font: string; fontSize: number | null; lineHeight: string };
  setDocumentBackground(opts: { image?: File | Blob | string | null; color?: string; repeat?: 'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'; attachment?: 'scroll' | 'fixed' }): Promise<DocumentBackground>;
  removeDocumentBackground(): this;
  getDocumentBackground(): DocumentBackground | null;
  showMenuBar(bool: boolean): this;
  toggleToolbar(): this;   // Ctrl+[
  toggleMenuBar(): this;   // Ctrl+]
  setUITemplate(name: 'classic' | 'ribbon'): this;
  getUITemplate(): 'classic' | 'ribbon';
  setIconTheme(name: string): this;
  getIconTheme(): string;
  setTableBorderColor(color: string): this;
  getTableBorderColor(): string;
  setTableLock(target: Element | WebEditorAPIModel | string, mode: 'size' | 'readonly' | null): boolean;
  getTableLock(target: Element | WebEditorAPIModel | string): 'size' | 'readonly' | null;
  setContentCSS(css: string): this;
  importWordFile(file: File): Promise<void>;
  importHwpxFile(file: File, options?: { mode?: 'cursor'|'append'|'replace'; silent?: boolean; maxTableWidth?: number; showLog?: boolean }): Promise<void>;
  pasteFromClipboard(): Promise<boolean>;
  isEmpty(): boolean;
  getSafeHTML(options?: { stripScript?: boolean; allowedTags?: string[]; allowedAttrs?: string[]; allowedStyles?: string[]; imageRewriter?: (src: string) => string; normalize?: boolean }): string;
  getAutoSaved(): string | null;
  clearAutoSaved(): this;
  getAutoSavedAsync(): Promise<string | null>;   // v2.6.8
  getAutoSaveBackend(): 'localStorage' | 'indexedDB' | 'custom' | null;
  showStorageInfo(): HTMLElement | null;   // v2.6.8
  saveNow(): this;
  saveToPDF(options?: { title?: string; hideToolbar?: boolean; css?: string }): void;
  saveToPDFInWindow(options?: { title?: string; css?: string }): void;
  saveToHTML(filename?: string, opts?: { standalone?: boolean; format?: 'document' | 'fragment'; css?: 'full' | 'minimal' | 'none'; title?: string }): void;   // v2.6.6.1
  printDocument(opts?: WebEditorPrintOptions): void;                 // v2.6.5 · title v2.6.6
  printHTML(html: string, opts?: WebEditorPrintOptions): void;
  previewDocument(opts?: WebEditorPrintOptions): Window | null;
  getContentStyle(): string;                                          // v2.6.5 — defaults for the viewer container
  watch(selector: string,
        handler: (changed: WebEditorAPIModel[], info: { reason: 'input' | 'api' | 'restore' | 'unknown'; all: boolean }) => void,
        opts?: { debounce?: number }): () => void;                          // v2.6.6
  silently<T>(fn: () => T): T;                                       // v2.6.6
  setZoom(ratio: number): this;
  getZoom(): number;
  validate(): Promise<{ profanity: any[]; privacy: any[] }>;
  maskSensitiveData(): Promise<number>;
  reviewSensitiveData(): Promise<number>;
  showStatusBar(bool: boolean): this;
  trapFocus(modalEl: Element, firstFocus?: Element | null): { release(): void };
  setFullscreen(bool: boolean): void;
  on(event: 'change', handler: (html: string) => void): this;
  on(event: 'tabChange', handler: (index: number) => void): this;
  on(event: 'focus' | 'blur' | 'selectionchange', handler: () => void): this;
  on(event: 'imageInserted' | 'imageUploaded', handler: (d: { src: string; file: File | null; node: HTMLImageElement }) => void): this;
  on(event: 'imageResized', handler: (d: { file: File | Blob; originalSize: number; resizedSize: number; originalWidth: number; originalHeight: number; width: number; height: number }) => void): this;
  on(event: 'zoom', handler: (d: { ratio: number }) => void): this;
  on(event: 'error', handler: (d: { context: string; error: Error }) => void): this;
  on(event: 'guard', handler: (d: { ok: boolean; blocked: boolean; items: any[]; counts: Record<string, number> }) => void): this;
  on(event: 'approvalform:change', handler: (d: { fields: Record<string, any>; changed: string[]; errors: ApprovalFormError[] }) => void): this;
  off(event?: string, handler?: Function): this;
  focus(): void;
  destroy(): void;
}

// Print / preview options (v2.6.6)
interface WebEditorPrintOptions {
  title?: string;   // <title> of the print document = default file name for "Save as PDF"; language default when omitted
}

// Added to the body element model (v2.6.6)
interface WebEditorAPIModel {
  duplicate(opts?: {
    ids?: 'strip' | 'keep' | ((oldId: string, index: number) => string | null | undefined);
    empty?: boolean | string;
    where?: 'after' | 'before' | 'end';
  }): WebEditorAPIModel | null;
  on(event: 'change', handler: (model: WebEditorAPIModel, info: { reason: string; all: boolean }) => void): (() => void) | null;
}

// approvalform add-on — attached to the editor when plugins:['approvalform'] (v2.6.6)
interface ApprovalFormError { id: string | null; field: string | null; reason: string; message: string; detail?: string }
interface ApprovalFormAPI {
  loadApprovalForm(html: string, opts?: { readOnly?: boolean }): void;
  attachApprovalForm(opts?: { readOnly?: boolean }): void;
  detachApprovalForm(): void;
  getApprovalFields(): Record<string, any>;
  validateApprovalForm(): { ok: boolean; errors: ApprovalFormError[] };
  recalcApprovalForm(): void;
  addApprovalRow(rowName?: string): WebEditorAPIModel | null;
  removeApprovalRow(rowName?: string): boolean;
}

12. Callback option reference

onInit(editor)

This is called once, after the editor finishes initialising.

onInit: (editor) => {
  editor.setHTML(savedContent);
  editor.resetModified();
}

onKeyDown(e) → boolean | void

This is called on keydown. Returning false prevents the default behaviour.

onKeyDown: (e) => {
  if (e.key === 'Tab') {
    return false;  // block the Tab key
  }
}

onBeforeCommand(command) → boolean | void

This is called just before an internal command runs. Returning false cancels the command.

onBeforeCommand: (cmd) => {
  if (cmd === 'insertTable') {
    return false;  // block table insertion
  }
}

onTabChange(index) → boolean | void

This is called just before the tab switches. Returning false cancels the switch.

onTabChange: (index) => {
  if (index === 1 && !userIsAdmin) {
    alert('You do not have permission to edit the HTML.');
    return false;
  }
}

uploadHandler(file) → Promise<string>

Handles uploading an image to your server. The handler must return the URL as a string.

uploadHandler: async (file) => {
  if (file.size > 10 * 1024 * 1024) {
    throw new Error('Files must be 10MB or smaller.');
  }
  const form = new FormData();
  form.append('upload', file);
  const res = await fetch('/api/file/upload', {
    method: 'POST',
    headers: { 'X-CSRF-Token': getCSRFToken() },
    body: form
  });
  if (!res.ok) throw new Error('Upload failed');
  const { url } = await res.json();
  return url;
}

13. Cross-browser issues and workarounds

IssueCauseWorkaround
Inconsistent Enter line-break tagBrowsers insert different tags (div / p / br)Initialises with execCommand('defaultParagraphSeparator', false, 'p').
Selection lost when clicking the toolbarThe click moves focus away from contenteditableApplies mousedown → e.preventDefault() on the toolbar.
fontSize execCommandResults differ between browsersApplies <span style="font-size:Xpt"> directly to the selected text.
Background colour commandChrome uses hiliteColor, while Firefox uses backColorBranches with try/catch.
Caret position on dropChrome / Safari and Firefox expose different APIsNormalises caretRangeFromPoint / caretPositionFromPoint.
Korean IME inputselectionchange fires unexpectedly during compositionGuards with a compositionstart/end flag.
Caret after inserting a table in SafariinsertNode resets the caretSets the caret explicitly in the first td.
Firefox drag-and-drop navigationBy default, the browser navigates away from the pageAdds e.stopPropagation() on dragover.

14. Board example (document preview)

14-1. Board write page

<!DOCTYPE html>
<html lang="ko">
<head>
  <link rel="stylesheet" href="/dist/webeditor.min.css">
</head>
<body>
  <form id="post-form">
    <input type="text" name="title" placeholder="Title">
    <div id="editor"></div>
    <input type="hidden" name="content" id="content-field">
    <button type="submit">Submit</button>
  </form>

  <script src="/dist/webeditor.min.js"></script>
  <script src="/dist/plugins/wordimport-native.min.js"></script>
  <script>
    const editor = new WebEditor('#editor', {
      height: '500px',
      defaultFont: 'Malgun Gothic',
      defaultFontSize: 14,
      showTableGuide: true,
      license: 'WED2-XXXX-XXXX-...',

      uploadHandler: async (file) => {
        const form = new FormData();
        form.append('file', file);
        const res = await fetch('/api/upload', { method: 'POST', body: form });
        return (await res.json()).url;
      },

      onInit: (ed) => {
        const existing = document.getElementById('existing-content');
        if (existing) { ed.setHTML(existing.innerHTML); ed.resetModified(); }
      }
    });

    document.getElementById('post-form').addEventListener('submit', async (e) => {
      e.preventDefault();                              // the check is async — block first, send once it passes

      // pre-submit check (banned words, personal data). Only meaningful with the guard option set.
      const r = await editor.guardBeforeSubmit();
      if (!r.ok) return;                                // banner stays up, submission stops

      // masking may have changed the content, so read it AFTER the check
      document.getElementById('content-field').value = editor.getHTML();
      e.target.submit();
    });

    window.addEventListener('beforeunload', (e) => {
      // preventDefault alone is ignored by some browsers — set returnValue too
      if (editor.isModified()) { e.preventDefault(); e.returnValue = ''; }
    });
  </script>
</body>
</html>

Making the viewer match the editor — the content-only stylesheet v2.6.5

If a saved post looks different on the viewing page, the saved HTML is fine and the receiving page needs adjusting. Two things need to match.

WhatWhereHow
Content rules (paragraph spacing, table borders, quotes, code blocks, Excel tables)dist/webeditor-content.css (+ .min.css)Load just this file on the viewing page and give the container class="we-content". It does not include toolbar, dialog or selection-outline rules.
Document defaults (default font, size, line height)editor.getContentStyle()These are set on the editing area itself and are not included in getHTML(). Store the string together with the body and apply it to the container's style.
// save — keep the defaults with the body
save({ html: editor.getSafeHTML(), style: editor.getContentStyle() });
// → 'font-family: Malgun Gothic; font-size: 10pt; line-height: 1.2;'

// viewing page
<link rel="stylesheet" href="dist/webeditor-content.min.css">
<div class="we-content" style="${doc.style}">${doc.html}</div>
The .we-content class name can be renamed with a single replace inside the file.

14-2. Pre-submit checks on a board (banned words & personal data)

Connecting the check to a board involves three places: the banned-word list (a config file), the editor options, and the submit button. The API itself is in 3-8, pre-submit check; this section explains where each piece goes on a board. For a working example, see demo/banned-words.js and demo/write.html.

// (1) the banned-word list — a global config file loaded BEFORE the core bundle
//     The point of this approach is not having to pass options on every page.
<script src="banned-words.js"></script>
<script src="/dist/webeditor.min.js"></script>

// inside banned-words.js
window.WebEditorBannedWords = ['word1', 'word2'];   // an array, or a JSON URL
window.WebEditorGuardAllow  = true;                // show [Allow] in the results dialog (default false)

// (2) editor options — what to detect, and what happens on submit
const editor = new WebEditor('#editor', {
  privacy:   { detect: ['ssn','phone','tel','intl-phone','email','credit-card','bank-account','biz-no','corp-no','passport','driver-license'] },
  profanity: { maskChar: '*' },              // words come from the global config above
  guard:     { notify: 'banner', block: true, mask: 'confirm' },
});

// (3) the submit button — save only once the check passes (same flow as 14-1)
const r = await editor.guardBeforeSubmit();
if (!r.ok) return;                       // banner stays up, submission stops
const body = editor.getHTML();          // masked content — read it AFTER the check

guard options

KeyValuesDefaultDescription
notify'banner' · 'notice' · 'both' · false'banner' banner is a bar that stays above the content (click an entry to jump to it); notice is a brief toast. With false, the check runs silently and nothing is shown on screen.
blocktrue · falsetrue Indicates whether a detection stops the submission with ok:false. With false it only reports and returns ok:true.
mask'confirm' · 'off''confirm' Indicates whether the banner offers [Review & mask]. Only the entries the user ticks are masked.
scope'all' · 'profanity' · 'privacy''all' Specifies which kinds count for the pre-submit check.
reveal'float' · 'scroll' · 'both' · false'float' Specifies extra alerting, used only when the banner is off-screen. 'float' shows a pinned bar with [Show me], 'scroll' scrolls to the banner and moves focus there, and 'both' does both.

Where the alerts appear — five distinct places

Five different surfaces can report a detection, and each is switched on by something different. To avoid reporting the same detection twice, it helps to tell them apart first. The following is what actually appears when you press [Insert sample] then [Save] in demo/write.html.

SurfaceSwitched on byWhat it showsHow it goes away
1. Banner above the content
.we-guard-banner
guard.notify: 'banner' default A message, counts, the list of detections (chips) and [Review & mask] ✕, ESC, or when nothing is left after masking
2. Toast
.we-notice--warn
guard.notify: 'notice' A message and counts only (no list) It does not fade by itself (timeout 0). It goes away at the next check or with clearGuardNotice().
3. Pinned bar
.we-guard-float
guard.reveal: 'float' default
— only when the banner is off-screen
A message, counts and [Show me] It goes away by itself once the banner scrolls into view.
4. Jump to the banner
(no surface of its own)
guard.reveal: 'scroll' Scrolls to the banner and moves focus there (screen readers announce it) —
5. Results dialog
.we-guard-dialog
The banner's [Review & mask] · the toolbar shield (guardScan) · the Tools menu A table of type & content with checkboxes, [Mask] [Allow] [<Prev] [Next>] [Close] [Close]
1 and 2 appear on submit; 5 is available at any time. Surfaces 1–4 belong to the submit flow and appear only when guardBeforeSubmit() finds something. Surface 5 is the check window the toolbar shield opens while writing. The banner's [Review & mask] reuses that same window, so there is one dialog, not two.

1. Listing the detections at the top — the banner

This is the default for guard.notify, so you do not need to switch anything on. Pressing [Save] with the sample content (mobile · email · resident number · card number · banned word) shows the following directly above the body.

⚠️  This cannot be submitted while items are detected     1 banned word · 4 personal data items    [ Review & mask ] [✕]
    [Mobile number 010-1234-5678] [Email address hong@example.com]
    [Resident registration number · check digit does not match 900101-1234567]
    [Credit card number 1234-5678-9012-3456] [Banned word ...]
  • Each chip is one detection, with the type on the left and the actual value on the right. Up to six are shown, and the rest are collapsed into N more.
  • Clicking a chip jumps to that spot in the body and selects the value. If the value is split across several tags (rare), a Could not locate it in the body. toast appears instead.
  • Resident, business and corporate registration numbers show check digit matches / does not match next to the type, so a value that merely fits the shape is distinguishable from a real one.
  • The heading depends on block: cannot be submitted when true, needs checking when false.
  • The banner is inserted inside wrapper before the body, so it never ends up in getHTML().

2. Alerting through a dialog — the results window

Instead of listing the detections in a banner, this shows them as a table the user can work through. There are two ways in.

// Way 1  the banner's [Review & mask] — present only while guard.mask is 'confirm' (the default).
guard: { notify: 'banner', mask: 'confirm' }   // 'off' reports without offering the button

// Way 2  the toolbar shield / Tools menu — any time while writing, unrelated to submitting
editor.reviewSensitiveData();                // the page can open it directly too

With the sample content, the window shows the following.

Content & privacy check results  (5 found · 5 selected)
 [x] │ Type                                                       │ Content
 [x] │ Mobile number                                              │ 010-1234-5678
 [x] │ Email address                                              │ hong@example.com
 [x] │ Resident registration number · check digit does not match  │ 900101-1234567
 [x] │ Credit card number                                         │ 1234-5678-9012-3456
 [x] │ Banned word                                                │ ...
          [ Mask ]  [ Allow ]  [ <Prev ]  [ Next> ]  [ Close ]
  • Only ticked rows are masked. All rows start ticked, and the count in the heading updates with the selection.
  • Long lists are paged, and that is when [<Prev] and [Next>] become active.
  • [Allow] appears only with window.WebEditorGuardAllow = true (see the note below).
  • When opened from the banner, closing the window re-runs the check and refreshes the banner; if nothing is left, it removes the banner and shows a No detected items remain. toast.

3. When the banner is off-screen — the pinned bar

On a board write screen, [Save] is at the very bottom of the page. When you submit from there, the banner appears above the body, i.e. off-screen, and to the user it looks as though nothing happened. guard.reveal covers that gap and does nothing when the banner is already visible.

guard: { reveal: 'float' }   // default — a pinned bar with [Show me]
guard: { reveal: 'scroll' }  // scroll to the banner and move focus there
guard: { reveal: 'both' }    // both
guard: { reveal: false }     // off — just the banner, even off-screen

⚠️  This cannot be submitted while items are detected   1 banned word · 4 personal data items   [Show me] [✕]

Three combinations to choose from on a board

Policyguard optionsWhat the user experiences
Block
(the demo, recommended)
{ notify: 'banner', block: true, mask: 'confirm' } Submission stops and the banner lists what was found. The writer needs to mask or delete the items before submitting.
Report only { notify: 'both', block: false } A banner and a toast report it, but the submission goes ahead (ok:true).
The page reports it itself { notify: false, block: true } + the 'guard' event The editor only makes the decision. You can show badges, modals or whatever matches the site.
// The third approach — the page owns the surface, the editor owns the verdict
const editor = new WebEditor('#editor', {
  guard: { notify: false, reveal: false, block: true },
});

editor.on('guard', r => {
  // r = { ok, blocked, items, counts:{ profanity, privacy } }
  if (!r.blocked) return myBadge.hide();
  myBadge.show(`${r.counts.profanity} banned · ${r.counts.privacy} personal`);
  myBadge.onClick = () => editor.reviewSensitiveData();   // borrow the dialog as it is
});

// The submit flow is unchanged — do not save when the check blocks
const r = await editor.guardBeforeSubmit();
if (!r.ok) return;
editor.clearGuardNotice();   // clears banner, pinned bar and toast at once (also before replacing the body)
[Allow] is opt-in for developers: the [Allow] button in the results dialog appears only when window.WebEditorGuardAllow = true (or profanity.allowButton). An allowance lasts for the current edit only (it is cleared on reload) and is based on the value, not the kind, because the personal-data patterns overlap (mobile ⊂ landline ⊂ bank account), so matching on kind as well would let a number allowed as a mobile get masked again as a landline. To mark posts submitted with allowances, see 14-4.
Phone numbers follow a standard set of formats: mobile (010-1234-5678 · +82 10-1234-5678), landline (Seoul 02-6719-6200 · regional 031~064 · VoIP 070 · toll-free 080 · safe numbers 050X · corporate 1588-1234 · parenthesised (02) 6719-6200 · international prefix +82-2-6719-6200) and international ('intl-phone': +1 (212) 555-0123 · +44 20 7946 0958). Separators may be -, . or a space. A phone-shaped number is never reported as a bank account, even when 'tel' is left out of detect.
Cannot-allow (hard block): some findings should never be allowed, whatever the author chooses. Put personal-data kinds in privacy.strict (or globally window.WebEditorGuardStrict = { types:[…], words:[…] }) and mark banned words with a leading ! in the word list (or profanity.strictWords). Those rows show 🔒 cannot allow in the review dialog and are not affected by the [Allow] button; they must be masked or removed before submitting. Example: window.WebEditorGuardStrict = { types: ['ssn','corp-no','biz-no','credit-card','bank-account'] }. editor.isGuardItemStrict({type, value}) lets you check the same thing from code.
Dates are not treated as bank accounts: the account pattern used to match YYYY-MM-DD and YY-MM-DD, so even a date inserted from the toolbar was reported. Anything outside month 1–12 or day 1–31 is not a date (2026-13-45 is still an account number).

Check again on the server — the browser check is not a gate

Everything above happens in the browser. That is enough to show writers what was found and give them a chance to fix it, but blocking is a different matter: anyone who knows the developer tools can post the form directly. If something must never get through, the server needs to check again just before saving.

Keep one list: if the banned-word list exists once for the browser and once for the server, the two will drift apart, and then you get “blocked on screen, accepted by the server”. Please have both read the same file (WebEditorBannedWords = '/config/banned-words.txt'). Keep the matching rules the same as well: case-insensitive, substring.
1. Remove the tags before matching

What reaches the server is HTML. Matching against it directly causes two problems: you hit tag names and attribute values, and you miss words that formatting has split, like id<b>iot</b>. Remove tags without leaving a space, so that a split word is joined back together.

// Java — drop script/style content, turn block ends into spaces
text = html.replaceAll("(?is)<(script|style)[^>]*>.*?</\1>", " ")
           .replaceAll("(?i)<(br|/p|/div|/li|/h[1-6]|/td|/tr)[^>]*>", " ")
           .replaceAll("<[^>]*>", "");           // remaining tags leave no gap
2. On the server, block a narrower set of personal data

We recommend not copying all eleven editor detectors to the server, for two reasons:

  • The screen has [Allow]. It exists because some values belong in the text, such as a company phone number or a contact address. If the server blocks those unconditionally, that option is lost, and if it trusts the allow list the client sent, checking on the server means nothing.
  • Types without a check digit produce false positives. The bank-account pattern matches dates, and a passport number looks like an order number. On screen a person decides; on the server, the writer is simply blocked with no explanation.
TypeHow to confirmOn the server
Resident / corporate / business registration numberits own check digit It is blocked, even if it was allowed with [Allow].
Credit card numberLuhnBlock
Email · phone · account · passport · driver licencenone It is handled on screen (mask / allow).

A value confirmed by a check digit is almost never a false positive, so it is safe to put beyond the reach of [Allow]. A resident registration number in a post does not become acceptable just because the writer says so. The screen catches more and the server blocks less, so nothing slips past the server that the screen would still have flagged.

Length alone cannot tell them apart: a Korean corporate registration number has the same shape as a resident registration number (13 digits, 6-7), and a business registration number looks like any ten digits. The check digit is what separates them — modulus 11 for resident, 10 for corporate, and the business number adds the tens digit of the ninth weighted product separately. When both match, count it as the more sensitive one (resident). And a placeholder such as 000000-0000000 sums to zero, which ‘matches’ a check digit of 0, so we recommend rejecting values made of a single repeated digit. Please apply the same rules to server-side checks (check digits · filtering values made of one repeated digit · resident registration number wins when both match).
Adding Luhn for cards is reasonable: the editor does not verify card numbers, because on screen a person can look and decide. The server cannot ask anyone. A real card number always passes Luhn, so nothing is missed, and an order number written in groups of four usually is filtered out here.
3. Keep the writer’s work when you block

There are two ways to reach the server check: a request that skipped the browser check, or a tab left open long enough that the browser holds an old word list. The second is not the writer’s fault, and an error page would lose everything they wrote. We recommend showing the compose screen again and reporting only what was found. Return the keys of files already uploaded as well, so they are re-attached on the next submit; otherwise, the files remain on the server without belonging to any post.

14-3. Board attachments & document preview (demo pattern)

This pattern adds file attachments (drag-and-drop, multiple) below the editor on the write screen, and opens an attached document in a new editor window with no menu bar or toolbar for previewing. It is used by the demos (demo/write.html, demo/view.html, demo/doc-preview.html).

The formats the preview handles

The extension decides how a file is handled. Documents go through the import pipeline and become editor content; images and videos skip conversion and are shown as-is without an editor (videos in a player).

ExtensionHandlingPlugin requiredPreview
.docximportWordFile()wordimportone content flow
.hwpimportHwpFile()hwpimportone content flow
.hwpximportHwpxFile()hwpximportone content flow
.xlsximportXlsxFile({ allSheets: true })xlsximportrebuilt as sheet tabs at the bottom
.pptximportPptxFile({ allSlides: true })pptimportrebuilt as slide tabs at the bottom
.md · .markdownimportMarkdownFile()markdownone content flow
.pdfimportPdfFile({ importMode: 'auto', pageBreaks: true })pdfimport (without it, the original is shown in the browser's <iframe> viewer)one content flow · page edges as page breaks
.png · .jpg · .gif · .webp · .bmp · .svg · .avif<img> (no conversion)nonethe image + format · width × height · file size
.mp4 · .m4v · .webm<video controls> (no conversion)nonea player (play · seek) + format · width × height · length · file size
Why PDF is different: the import packs exist to turn a document into editable content. With the pdfimport plugin loaded (v2.6.7), PDF now goes through the same path — text pages become paragraphs and tables, scanned pages become images. Without the plugin the original is left to the browser's built-in viewer (<iframe>); note that phones and tablets often have no built-in PDF viewer (or render only the first page), which leaves the frame blank, so the demo shows open-in-new-tab / download links there instead.
// 1) attachments: keep the chosen File as a Blob and save it with the post (no base64)
attachments.push({ name: file.name, size: file.size, type: file.type, blob: file });
// save: await BoardStore.save({ ...post, attachments }) — demo/board-store.js, browser IndexedDB

// 2) the preview window (doc-preview.html) — an editor with no menu bar or toolbar
const editor = new WebEditor('#pv-editor', {
  menubar: false,                                  // no dropdown menu bar
  plugins: ['format','image','table','link',
            'wordimport','hwpximport','xlsximport','pptimport','markdown'],
});
editor.showToolbar(false);                          // hide the toolbar icons
editor.setHeight(window.innerHeight - 46);          // fixed height + internal scrolling (required)

// blob: the attachment the parent window sent with the postMessage in 7)
// 3) PDF is not converted — it goes straight to the browser viewer, not the import pipeline
if (/\.pdf$/i.test(name)) {
  const url = URL.createObjectURL(blob);
  document.getElementById('pv-pdf').src = url;             // <iframe>
  // revokeObjectURL(url) when the window closes or another file is opened
  return;
}

// 3-1) videos are not converted either — put the blob: address straight into <video> (plays without a download, seeks with the play bar)
if (/\.(mp4|m4v|webm)$/i.test(name)) {
  const v = document.createElement('video');
  v.controls = true; v.preload = 'metadata'; v.setAttribute('playsinline', '');
  v.addEventListener('loadedmetadata', () => { /* show v.videoWidth × v.videoHeight · v.duration below */ });
  v.addEventListener('error', () => { /* a codec the browser cannot decode (e.g. H.265) — offer the download */ });
  v.src = URL.createObjectURL(blob);
  document.getElementById('pv-editor').replaceChildren(v);   // no editor is created
  return;
}

// 4) wrap the received Blob in a File and import by format
const file = new File([blob], name, { type: mime });
const opt  = { silent: true, mode: 'replace', showLog: false };   // a viewer: no log, no dialog

if      (/\.hwpx$/i.test(name))         await editor.importHwpxFile(file, opt);
else if (/\.xlsx$/i.test(name))         await editor.importXlsxFile(file, { ...opt, allSheets: true });
else if (/\.pptx$/i.test(name))         await editor.importPptxFile(file, { ...opt, allSlides: true });
else if (/\.(md|markdown)$/i.test(name)) await editor.importMarkdownFile(file, { mode: 'replace' });
else                                    await editor.importWordFile(file, opt);

// 5) XLSX and PPTX arrive as one long column — rebuild them as sheet / slide tabs
if (/\.(xlsx|pptx)$/i.test(name)) setupSheetTabs(editor);

// 6) lock last — locking while the import is still writing would cut the conversion short
editor.setReadOnly(true);   // blocks editing, the menu bar, table/image context menus, and resizing
editor.setHeight(window.innerHeight - 46);   // re-fix the height the conversion grew (keeps internal scrolling)

// 7) parent → preview window: a same-origin postMessage handshake
// the preview opens as a popup window 1000px wide by default
const w = window.open('doc-preview.html', '_blank', 'width=1000,height=860,resizable=yes,scrollbars=yes');
window.addEventListener('message', e => {
  if (e.source === w && e.data.type === 'docPreviewReady')
    w.postMessage({ type: 'docPreviewFile', name, mime, blob }, location.origin);   // a Blob crosses over as is (structured clone)
});
Preview scrolling: the height option only applies min-height to the body (which then grows), so if you want a fixed height that fills the window with internal scrolling, call setHeight(px) after creating it (without it, the body overflows the window and cannot be scrolled). importWordFile(), importHwpxFile(), and importMarkdownFile() each require their own bundle: wordimport, hwpximport, and markdown. In the demos, attachment and preview data are handled only through browser storage (IndexedDB) and same-origin postMessage (in production, replace this with a file upload API).
Attachment size: the demo stores attachments as Blobs in the browser's IndexedDB (demo/board-store.js). The limit is the quota the browser grants from free disk space (usually gigabytes), and the list page shows how much the board uses and how much is free. Attachments are accepted up to 20MB per file. Where IndexedDB is unavailable (some private modes or security settings) the board falls back to localStorage (about 5MB, base64) as before. Clear it before and after a demo with [Reset board] on the list page (14-7). This is a demo convenience; in production, please use an upload API and file URLs.

Inside the preview window (doc-preview.html)

The preview window sends a ready signal to its opener, receives the file data, and then performs steps 2 and 3 above (create the editor → import → setReadOnly(true)). Since editing is not the goal, the sourceview plugin — which draws the Edit / HTML / Preview tab bar — is left out.

// doc-preview.html — the preview-only window (the child)
// (1) once loaded, signal readiness to the opener
if (window.opener)
  window.opener.postMessage({ type: 'docPreviewReady' }, location.origin);

// (2) receive the file data — verify same origin and opener
window.addEventListener('message', async e => {
  if (e.origin !== location.origin) return;              // same origin only
  if (window.opener && e.source !== window.opener) return;
  if (!e.data || e.data.type !== 'docPreviewFile') return;

  const { name, mime } = e.data;
  // the basic demo board sends the Blob itself; the older dataUrl message is still accepted
  const blob = e.data.blob instanceof Blob ? e.data.blob : await (await fetch(e.data.dataUrl)).blob();
  // videos go to a player with no editor — same as 3-1) above
  if (/\.(mp4|m4v|webm)$/i.test(name)) return loadVideo(URL.createObjectURL(blob), name, blob.size);
  // create the viewer editor — no menu bar or toolbar, and no sourceview tab bar
  const ed = new WebEditor('#pv-editor', {
    menubar: false,
    plugins: ['format','image','table','link',
            'wordimport','hwpximport','xlsximport','pptimport','markdown'],
  });
  ed.showToolbar(false);
  ed.setHeight(window.innerHeight - 46);

  const file = new File([blob], name, { type: mime });
  if (/\.hwpx$/i.test(name))          await ed.importHwpxFile(file, { silent: true, mode: 'replace', maxTableWidth: 960 });
  else if (/\.(md|markdown)$/i.test(name)) await ed.importMarkdownFile(file, { mode: 'replace' });
  else                              await ed.importWordFile(file, { silent: true, mode: 'replace' });

  ed.setReadOnly(true);   // fully block editing (viewer mode)
});
Opening the preview window (from the parent): window.open('doc-preview.html', '_blank', 'width=1000,height=860,resizable=yes,scrollbars=yes'). Specifying a width and height opens a separate popup window rather than a tab (default width 1000px). Read-only mode (setReadOnly(true)) blocks not just body editing but also the menu bar, table and image context menus, and resizing, which suits a reference viewer.
Video preview: the demo holds attachments as Blobs, so it uses the URL.createObjectURL(blob) address directly as the <video> src. The browser reads only the parts it needs, so the video plays without a download and seeks with the play bar. Whether it plays depends on whether the browser supports its codec — mp4 with H.264 (AVC) · AAC and webm with VP8/VP9 · AV1 play in the major browsers, while H.265 (HEVC) and others fall into error in some browsers, so keep a message and the download next to the player. Boards that store files on a server (the JSP · Spring samples) have no Blob, so their preview window uses an address that supports Range (206) (/attach/stream?v=…) as the src. With a download address that sends the whole file, the video plays but cannot seek, and Safari (iOS) will not play it.

14-4. Security marker in the board list (demo pattern)

This pattern puts a ▲ Security marker in the board list on posts where the author used [Allow] to let a finding through, so a reviewer can see at a glance that something was flagged and then allowed.

Just before saving, read what was allowed with editor.getGuardAllowList() and keep only the kinds and counts on the post.

const list = editor.getGuardAllowList();
const guardAllowed = list.length ? {
  profanity: list.filter(i => i.type === 'banned').length,
  privacy:   list.filter(i => i.type !== 'banned').length,
  types:     [...new Set(list.map(i => i.type))],
} : null;

⚠️ Please do not store the allowed values themselves. Keeping an allowed phone number or email in the post metadata would make a privacy feature copy the very data it manages into storage a second time. The kinds and counts already show what was allowed.

14-5. Multiple instances

// licenses are applied per instance through the license option
const editor1 = new WebEditor('#editor-1', { height: '300px', license: 'WED2-...' });
const editor2 = new WebEditor('#editor-2', { height: '300px', readOnly: true, license: 'WED2-...' });

// copy the first editor's content into the second
const html = WebEditor.getAPIModelByIndex(0).getHTML();
WebEditor.getAPIModelByIndex(1).setHTML(html);

14-6. PDF preview — basic preview & DEXT-PDF preview

Overview

There are two ways to preview a PDF attached to a board post. Basic preview shows the original file in the browser's built-in PDF viewer and needs no extra product. DEXT-PDF preview opens the document in the DEXT-PDF viewer component and adds rotate, delete, reorder, pen, highlight and merged view. Dee Editor itself is not involved in either; only the preview window is set up separately.

Components

ElementMeaning
Basic previewRefers to the PDF path of demo/doc-preview.html. The file becomes a Blob URL and is placed in an <iframe>.
DEXT-PDF previewRefers to viewer.jsp in the JSP board. It opens the attachment with a <dext-pdf-editor> element; the server assembles edited results.
PDF import (pdfimport)Refers to the plugin that converts a PDF into body content instead of previewing it. When it is loaded in the preview window it takes precedence over basic preview (see 14-3).

Basic preview

The attachment is read as a Blob, its type is set to application/pdf, and the address from URL.createObjectURL() is loaded into an <iframe>. Mobile and tablet browsers either have no built-in viewer or draw only the first page inside a frame, so on those devices the preview is replaced by Download / Open in new tab.

FunctionDescription
loadPdf(d)Turns the attachment into a Blob URL and shows it in <iframe class="pv-pdf">.
canRenderPdfInline()Tells whether the whole PDF can be drawn inside a frame. Returns true only on desktop with navigator.pdfViewerEnabled === true.
pdfFallback(d, mount)Shows Download and Open-in-new-tab buttons when the built-in viewer cannot be used.

Basic preview example

function canRenderPdfInline() {
  if (isMobileOrTablet()) return false;          // iPadOS reports Macintosh — check maxTouchPoints
  return navigator.pdfViewerEnabled === true;   // old browsers (undefined) are excluded
}

const blob = await (await fetch(d.dataUrl)).blob();
const pdf  = blob.type === 'application/pdf' ? blob : new Blob([blob], { type: 'application/pdf' });
const url  = URL.createObjectURL(pdf);

if (!canRenderPdfInline()) { pdfFallback(d, mount); return; }
const ifr = document.createElement('iframe');
ifr.className = 'pv-pdf';
ifr.src = url;
mount.appendChild(ifr);

The type is set explicitly so that the built-in viewer recognizes the PDF even when the attachment's MIME type is empty or application/octet-stream. Release the address with URL.revokeObjectURL(url) when the window closes or another document opens.

DEXT-PDF preview

Clicking a PDF attachment on the board's view or write page opens the viewer window with window.open(CP + '/viewer.jsp?post=…&v=…'). The viewer window defines the global window.DEXT_PDF_CONFIG first and then loads the DEXT-PDF module. If the module is evaluated before the configuration, it cannot read it, so please keep this order.

Viewer configuration example

<script>
window.DEXT_PDF_CONFIG = {
  theme: 'light',
  lang: 'en',            // pass the board's UI language
  sidebar: 'visible',
  mode: 'text',
  zoom: 'fit-page',
  features: null          // set per page with the element's features attribute
};
</script>
<script type="module" src="dext-pdf/dext-pdf.js"></script>

Precedence is element attribute > global configuration > component default.

Opening a document example

const FEATURES = 'rotate,delete,reorder,ink,highlight,search,print,help';

customElements.whenDefined('dext-pdf-editor').then(() => {
  const editor = document.createElement('dext-pdf-editor');
  editor.setAttribute('features', FEATURES);
  document.body.appendChild(editor);
  return editor.open(CP + '/attach/download?v=' + vindex + '&inline=true', password ? { password } : undefined);
}).catch(e => {
  if (e && e.name === 'PasswordException') askPassword();   // protected file — ask and reopen
});

The attachment is downloaded by its attachment number (vindex). For a password-protected file, catch PasswordException, ask for the password and open the file again.

Server API

Merging PDFs and assembling edited results are done by the DEXT-PDF engine on the server. The board sample provides these requests through PdfServlet (/pdf/*).

RequestDescription
GET /pdf/facts?post=Returns the page count, whether it is a PDF and whether it has a password, for each attachment of the post.
POST /pdf/mergeMerges the selected attachments (keys) and responds with one PDF. The result is not stored; the size limit is pdf.maxMergeBytes (200MB by default).
POST /pdf/assemble?post=&name=Builds a new PDF from the viewer's getEditScript() result (rotate, delete, reorder, pen, highlight).

The server accepts only the post's own attachments as sources. A file opened in the viewer directly from the user's PC cannot be saved because the server cannot find its source; please upload it as an attachment first. For server memory, see the minimum server spec in jsp-board/README.md.

Choosing a method

SituationRecommended
Only reading the originalBasic preview. It needs no extra product and adds no server load.
Same view needed on mobile and tabletDEXT-PDF preview. On those devices, basic preview shows a download prompt instead.
Page rotate / delete / merged view / pen marks neededDEXT-PDF preview.
PDF content must be edited as body textPDF import (9-J).

14-7. Demo board storage & board reset (demo pattern)

Overview

The basic demo board stores posts and attachments in the browser's IndexedDB so it works without a server. Saving and loading are handled by the shared module demo/board-store.js (BoardStore); the list, write and view pages call only this module. Attachments are stored as files (Blobs), not base64, so they do not grow, and the limit is the quota the browser grants from free disk space (usually gigabytes). Posts saved by earlier releases in localStorage (about 5MB) are moved over once, when the new board is first opened.

Structure

PartDescription
DB dee-demo-boardThe board database. The Korean and English boards share it.
postsThe store that holds one record per post. Attachment entries hold only the name, size, type and fileId.
filesThe store that holds the attachment files (Blobs). They are removed with the post, or when an attachment is removed while editing.
FallbackWhere IndexedDB cannot be opened (some private modes or security settings), the board saves to localStorage as before (key we_board_posts, about 5MB).

BoardStore functions

FunctionDescription
list()Returns the posts. Attachment files are not read.
get(id, { files: true })Returns one post. With files: true it also reads attachments[i].blob.
save(post)Saves one post. Pass new attachments with a blob and no fileId. Returns true, or reports the cause and returns false.
remove(id)Deletes a post and its attachments. Returns true / false.
usage()Returns how much the board uses and the browser quota (navigator.storage.estimate()).
reset()Deletes all board data (the DB and the old localStorage key). Other demos keep their data.

Saving example

// if saving or deleting fails, stay on the page without a success message (the draft is kept)
const post = { id, title, author, date, body: editor.getHTML(), attachments, savedAt: new Date().toISOString() };
if (!(await BoardStore.save(post))) return;
showToast('Saved.');

// view page — read only this post's attachment files and build download links
const full = await BoardStore.get(id, { files: true });
full.attachments.forEach(a => { a.href = URL.createObjectURL(a.blob); });

Board reset & usage

ItemDescription
[Reset board] buttonThe button under the list. After you confirm, it deletes every post and attachment. Please note that this cannot be undone.
board.html#resetOpens the same reset confirmation from the address. This is handy as a bookmark on a demo PC, and it never deletes anything without confirmation.
Usage lineOne line under the list showing how much the board uses and the space left in this browser. On the fallback it reads "limit about 5 MB".
Attachment limit20MB per file. Because preview and import handle files in memory, an unlimited setting is not available.
Demo-only structure: posts in browser storage are visible only in that browser and can be removed when site data is cleared. In production, keep posts in a server database and upload attachments and body images to the server (uploadHandler). For limits and fallback behaviour, see “Demo board storage limits” in the deployment guide (DEPLOY.md).

Appendix — Toolbar command list

The command names you can put in the toolbar array (and in a config built with demo/ui-config.html). '|' is a separator. If the required plugin is missing from plugins, that button is not rendered.

new WebEditor('#editor', {
  toolbar: [
    ['newDocument', 'openHTML', '|', 'wordImport', 'hwpxImport', '|', 'save', 'printContent'],
    ['bold', 'italic', 'underline', '|', 'insertImage', 'insertTable', 'insertLink']
  ]
});
CommandDescriptionRequired plugin
File
newDocumentNew documentcore
openHTMLOpen (HTML file)core
importDocumentImport document (unified)importMode:'unified', or list it in the toolbar array
wordImportImport MS Wordwordimport
hwpImportImport Hangul HWPhwpimport
hwpxImportImport Hangul HWPXhwpximport
xlsxImportImport Excel XLSXxlsximport
pptImportImport PowerPoint PPTXpptimport
pdfImportImport PDF (Beta)pdfimport
markdownImportImport Markdownmarkdown
ocrImportText recognition (OCR), available only when the engine (dext-ocr/) is presentocr
saveSave (download HTML)core
saveAsPDFSave as PDFcore
printContentPrintcore
Edit & tools
undoUndocore
redoRedocore
selectAllSelect allcore
caseUpperConvert to uppercasecore
caseLowerConvert to lowercasecore
removeFormatClear formattingformat
findReplaceFind / replacefind
guardScanContent & privacy checkcore (content-guard)
showStorageInfoBrowser storage window. It is not in the automatic layout and appears when listed in the array (5-5)core
Insert
insertImageInsert imageimage
imageEditEdit image (DEXT Image; opens the selected image)core (image) — hidden when imageEditor:false
documentBackgroundDocument background imagedocbg
insertDateTimeInsert date/time (with format picker)insert
insertVideoVideo / YouTubevideo
insertShapeInsert shapeshape
insertChartInsert chart (edits the selected chart) v2.7.3.0chart
emojiEmojiemoji
specialCharSpecial charactersinsert
insertTableInsert tabletable
insertLinkInsert linklink
removeLinkRemove linklink
insertHRDividerinsert
insertBlockquoteBlock quoteinsert
insertCodeBlockCode blockinsert
insertPageBreakPage breakinsert
Format
paragraphStyleParagraph style (select)format
fontFamilyFont (select)format
fontSizeFont size (select)format
lineHeightLine spacing (select)format
fontSizeUpIncrease font sizeformat
fontSizeDownDecrease font sizeformat
boldBoldformat
italicItalicformat
underlineUnderlineformat
strikeThroughStrikethroughformat
superscriptSuperscriptformat
subscriptSubscriptformat
fontColorFont colourformat
highlightColorHighlight colourformat
justifyLeftAlign leftformat
justifyCenterAlign centerformat
justifyRightAlign rightformat
justifyFullJustifyformat
indentIndentformat
outdentOutdentformat
insertOrderedListNumbered listformat
insertUnorderedListBulleted listformat
Forms (approvalform add-on)
afAddRowAdd form row (clones the data-af-row row under the caret)approvalform
afRemoveRowRemove form row (the last row is kept)approvalform
When you set toolbar, only the commands in that array are rendered (automatic layout is skipped). If it is left unset, buttons from the loaded plugins are placed automatically by row and order.
importDocument (unified document import) is hidden from the automatic layout; you can turn it on with importMode: 'unified', or put it in the toolbar array yourself (see importMode in §2).

Appendix — Keyboard shortcuts

ShortcutAction
Ctrl+BBold
Ctrl+IItalic
Ctrl+UUnderline
Ctrl+KInsert hyperlink
Ctrl+FFind / replace
Ctrl+ZUndo
Ctrl+YRedo
Ctrl+Shift+ZRedo (Mac style)
Ctrl+ASelect all
Ctrl+CCopy
Ctrl+XCut
Ctrl+VPaste
Ctrl+Shift+VPaste as plain text
Ctrl+[Toggle the toolbar
Ctrl+]Toggle the menu bar
Ctrl+NNew document
Ctrl+OOpen (HTML file)
Ctrl+SSave (download HTML) — also works in read-only mode
Ctrl+PPrint (document body only)
F11Toggle full screen (Esc to leave)
Esc (with text selected)Close the selection toolbar (inlineToolbar); the selection stays as it is
Tab (inside a table)Move to the next cell
Del (with cells selected)Clear the cell contents

Appendix — File structure

⭐ marks the files you actually need in production. Load the opt-in extension packs only when you use that feature.

Distribution files (dist/)

dist/
├── webeditor.js              UMD development bundle (readable)
├── webeditor.min.js          UMD production bundle ⭐
├── webeditor.esm.js          ES module bundle (for import)
├── webeditor.css             Stylesheet (readable)
├── webeditor.min.css
├── webeditor-content.css / .min.css   Content-only rules for viewing pages (§14-1) ⭐
├── webeditor.d.ts            TypeScript type definitions
├── locales/
│   └── ja.js / .min.js       Japanese language pack (§10-A-4)
└── plugins/                  Extension packs — load only what you need
    ├── wordimport-native.js / .min.js      MS Word (.docx) import ⭐
    ├── hwpimport-native.js / .min.js       Hangul (.hwp) import ⭐
    ├── hwpximport-native.js / .min.js      Hangul (.hwpx) import ⭐
    ├── xlsximport-native.js / .min.js      Excel (.xlsx) import ⭐
    ├── pptimport-native.js / .min.js       PowerPoint (.pptx) import ⭐
    ├── pdfimport-native.js / .min.js       PDF (.pdf) import ⭐ Beta (in-house parser · DEXT-PDF integration)
    ├── markdown-native.js / .min.js        Markdown import / export ⭐
    ├── ocr-native.js / .min.js             Text recognition (OCR) connector — the dext-ocr/ engine is separate (§9-L)
    ├── approvalform.js / .min.js           Approval / application form field engine (about 23 KB, §9-H)
    ├── approvaldesigner.js / .min.js       Approval form designer — field panel · ids · form definition · tidy tables (about 65 KB, §9-H-4)
    └── markdown-engine.js / .min.js        Markdown conversion engine (standalone)
Extension bundleplugins valueAPI it provides
wordimport-native.min.js'wordimport'importWordFile()
hwpimport-native.min.js'hwpimport'importHwpFile()
hwpximport-native.min.js'hwpximport'importHwpxFile()
xlsximport-native.min.js'xlsximport'importXlsxFile()
pptimport-native.min.js'pptimport'importPptxFile()
pdfimport-native.min.js'pdfimport'importPdfFile() (Beta)
ocr-native.min.js'ocr'ocrInsert() · extractTextFromImage() · setOcrProvider() · getOcrProviders() (§9-L)
markdown-native.min.js'markdown'importMarkdownFile() · setMarkdown() · getMarkdown() · viewMarkdown()
approvalform.min.js'approvalform'loadApprovalForm() · attachApprovalForm() · detachApprovalForm() · getApprovalFields() · validateApprovalForm() · recalcApprovalForm() · addApprovalRow() · removeApprovalRow() (§9-H)
approvaldesigner.min.js'approvaldesigner'openFormDesigner() · closeFormDesigner() · setFieldProps() · clearFormField() · lockFormHeaders() · insertSignPlaceholder() · listFormFields() · getFormDefinition() · markRepeatRow() · lintForm() · fixForm() · previewForm() · importFormDocument() · tidyForm() · useTableAsSign() · exportFormJson() (§9-H-4)
Shapes ('shape'), emoji, special characters, find & replace, document backgrounds, and source view are part of the core bundle, so no extra file is needed. Just add the name to the plugins array.
If you list a name in plugins without loading its bundle, the feature is silently disabled and the related API calls reject, with a loading hint printed to the console.
ZIP extraction for document import (Word, HWPX, XLSX and PPTX) uses the browser's built-in DecompressionStream, so there is no external compression library.

Loading example

<!-- core (required) -->
<link rel="stylesheet" href="dist/webeditor.min.css">
<script src="dist/webeditor.min.js"></script>

<!-- extension packs (only what you use) -->
<script src="dist/plugins/wordimport-native.min.js"></script>
<script src="dist/plugins/hwpximport-native.min.js"></script>
<script src="dist/plugins/xlsximport-native.min.js"></script>
<script src="dist/plugins/pptimport-native.min.js"></script>
<script src="dist/plugins/markdown-native.min.js"></script>

<script>
new WebEditor('#editor', {
  plugins: ['format', 'image', 'table', 'link', 'video',
            'shape', 'emoji', 'insert', 'find', 'docbg', 'sourceview',   // in the core
            'wordimport', 'hwpximport', 'xlsximport', 'pptimport', 'markdown']  // extension packs
});
</script>

© 2024-2026 DEXTSOLUTION Inc. All Rights Reserved.