You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TinyMCE:如何判断用户输入了新行?

Troubleshooting Your TinyMCE Empty Line Logging

Hey there! Let's break down why your current implementation might be struggling and fix it up to reliably log when a new empty line is added in TinyMCE.

First, Let's Spot the Issues in Your Current Code

  1. Incorrect Logical Operator: You've got && in your condition — that's an HTML-escaped version of &&, which will throw a syntax error in TypeScript. You need to use the plain && operator instead.
  2. Global Key Listener: Listening to window:keyup triggers for every Enter press on the page, not just those inside your TinyMCE editor. This can lead to false positives or missed cases if the editor isn't active.
  3. Fragile Text Node Check: Checking just the characters around the selection's start offset doesn't account for how TinyMCE structures empty lines (usually as empty block elements like <p> or <p>&nbsp;</p>). This logic will fail when the cursor is directly in an empty block.

Improved Implementation Options

Option 1: Use TinyMCE's Built-in Editor Events (Recommended)

TinyMCE has its own event system that's far more reliable for editor-specific actions. Here's how to set up a listener directly in the editor's setup config:

// In your TinyMCE initialization code
tinymce.init({
  // Your existing editor configuration (selector, plugins, etc.)
  setup: (editor) => {
    // Listen for Enter key presses inside the editor
    editor.on('keydown', (event) => {
      if (event.key === 'Enter') {
        // Check if we're starting from an empty line
        const selectedNode = editor.selection.getNode();
        if (selectedNode.tagName === 'P' && selectedNode.textContent.trim() === '') {
          console.log('Enter hit on empty line');
        }

        // Also check after the keyup to catch the newly created empty line
        editor.once('keyup', () => {
          const currentNode = editor.selection.getNode();
          if (currentNode.tagName === 'P' && currentNode.textContent.trim() === '') {
            console.log('New empty line created');
          }
        });
      }
    });
  }
});

Option 2: Fix Your Angular Host Listener

If you prefer to stick with the @HostListener approach, here's a revised version that addresses the issues:

@HostListener('window:keyup', ['$event']) 
keyEvent(event: KeyboardEvent) {
  // Exit early if no active TinyMCE editor or the key isn't Enter
  if (!tinymce.activeEditor || event.key !== 'Enter') return;

  const editor = tinymce.activeEditor;
  const range = editor.selection.getRng(true);
  const startContainer = range.startContainer;

  // Check if we're in a text node with empty surrounding characters
  let isEmptyLine = false;
  if (startContainer.nodeType === Node.TEXT_NODE) {
    const text = startContainer.textContent || '';
    isEmptyLine = text.substring(range.startOffset - 1, range.startOffset) === '' 
      && text.substring(range.startOffset, range.startOffset + 1) === '';
  } else {
    // Check if the element itself is an empty block (like an empty <p>)
    isEmptyLine = startContainer.textContent.trim() === '';
  }

  // Also verify the parent block element in case the cursor is at the edge
  const parentBlock = editor.dom.getParent(startContainer, 'p, div');
  if (parentBlock && parentBlock.textContent.trim() === '') {
    isEmptyLine = true;
  }

  if (isEmptyLine) {
    console.log('Enter hit on empty line');
  }
}

Key Improvements in These Solutions

  • Editor-Specific Context: We first check if there's an active TinyMCE editor to avoid running logic for unrelated Enter presses.
  • Block Element Checks: We target the actual block elements (like <p> tags) that TinyMCE uses for lines, which is a more reliable way to detect empty lines.
  • Proper Logical Operators: Fixed the syntax error with the logical AND operator.

内容的提问来源于stack exchange,提问作者RyeGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:28:36