Plain Text Clipboard

Tự động chuyển text copy về dạng thuần text, loại bỏ font, màu sắc, định dạng HTML.

K instalaci tototo skriptu si budete muset nainstalovat rozšíření jako Tampermonkey, Greasemonkey nebo Violentmonkey.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat manažer uživatelských skriptů.

(Už mám manažer uživatelských skriptů, nechte mě ho nainstalovat!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Už mám manažer uživatelských stylů, nechte mě ho nainstalovat!)

// ==UserScript==
// @name         Plain Text Clipboard
// @namespace    https://github.com/plain-text-clipboard
// @version      2.0.0
// @description  Tự động chuyển text copy về dạng thuần text, loại bỏ font, màu sắc, định dạng HTML.
// @author       Claude
// @match        *://*/*
// @run-at       document-start
// ==/UserScript==

(function () {
  'use strict';

  function htmlToPlainText(html) {
    const div = document.createElement('div');
    div.innerHTML = html;

    div.querySelectorAll('br').forEach(br => br.replaceWith('\n'));
    div.querySelectorAll('p, div, li, tr, h1, h2, h3, h4, h5, h6, blockquote').forEach(el => {
      el.prepend('\n');
    });

    return (div.innerText || div.textContent || '')
      .replace(/\r\n/g, '\n')
      .replace(/\r/g, '\n')
      .replace(/[ \t]+/g, ' ')
      .replace(/\n{3,}/g, '\n\n')
      .trim();
  }

  document.addEventListener('copy', (e) => {
    const selection = window.getSelection();
    if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return;

    let htmlContent = '';
    try {
      const range = selection.getRangeAt(0);
      const fragment = range.cloneContents();
      const tempDiv = document.createElement('div');
      tempDiv.appendChild(fragment);
      htmlContent = tempDiv.innerHTML;
    } catch {
      return;
    }

    if (!/<[a-z][\s\S]*>/i.test(htmlContent)) return;

    const plainText = htmlToPlainText(htmlContent);
    if (!plainText) return;

    try {
      e.preventDefault();
      e.clipboardData.setData('text/plain', plainText);
      e.clipboardData.setData('text/html', '');
    } catch {}
  }, true);

})();