← 返回文章列表

解决gemini 拷贝到OneNote 单词保持高亮完美解决方案 篡改猴 + stylebot+ multi words highlit

2026年05月17日 00:58:43 星期日 问题,ChatGPT重新输出 篡改猴代码生效后,过一段时间又失效了。

md 代码高亮测试2026年10月12日 21:55:47 星期一

// JavaScript syntax highlighting test
const name = "Allen";
const count = 42;

function greet(user) {
  if (user) {
    console.log(`Hello ${user}`);
  }
  return true;
}

重新代码 加入 Site Unreachable

// ==UserScript==
// @name         Gemini & NiceAIGC Highlight Copy to OneNote Stable
// @namespace    http://tampermonkey.net/
// @version      5.2
// @description  稳定保留 Gemini / NiceAIGC / FindManyStrings 高亮和行内代码复制到 OneNote
// @match        https://gemini.google.com/*
// @match        https://*.nice188.com/*
// @match        *://*/*
// @include      about:blank
// @include      about:srcdoc
// @grant        none
// @run-at       document-start
// @allFrames    true
// ==/UserScript==

(function () {
    'use strict';

    /*
     * 说明:
     * 1. @match *://*/* 是为了兼容 nice188 聚合平台里的动态 iframe。
     * 2. 下面 shouldRun() 会做限制,避免脚本在无关网页里乱生效。
     * 3. 页面显示只注入 CSS,不直接替换 Gemini / NiceAIGC 的真实 DOM。
     * 4. 复制时临时生成一份 OneNote 友好的 HTML,强制写入剪贴板。
     */

    function shouldRun() {
        const href = String(location.href || '');
        const host = String(location.hostname || '');
        const referrer = String(document.referrer || '');

        if (host === 'gemini.google.com') return true;
        if (host.endsWith('.nice188.com') || host === 'nice188.com') return true;

        if (referrer.includes('gemini.google.com')) return true;
        if (referrer.includes('nice188.com')) return true;

        if (href === 'about:blank' || href === 'about:srcdoc') {
            if (referrer.includes('gemini.google.com')) return true;
            if (referrer.includes('nice188.com')) return true;
        }

        return false;
    }

    if (!shouldRun()) return;

    const STYLE_MAP = {
        0: { bg: '#ffff00', fg: '#000000', weight: '700' },
        1: { bg: '#ffc400', fg: '#000000', weight: '700' },
        2: { bg: '#ff0000', fg: '#ffffff', weight: '700' },
        3: { bg: '#3f8cff', fg: '#ffffff', weight: '700' }
    };

    const CODE_STYLE = [
        'color:#df38dd !important',
        'background-color:#f3f3f3 !important',
        'background:#f3f3f3 !important',
        'font-family:Consolas, Monaco, monospace !important',
        'padding:2px 5px !important',
        'border-radius:3px !important',
        'font-size:0.9em !important',
        'display:inline !important',
        'white-space:pre-wrap !important'
    ].join(';');

    function getElement(node) {
        if (!node) return null;
        return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
    }

    function getHighlightStyleIndex(el) {
        if (!el) return null;

        const className = String(el.className || '');
        const match = className.match(/FindManyStrings-style-(\d+)/);

        if (!match) return null;
        return Number(match[1]);
    }

    function applyHighlightStyle(el) {
        const styleIndex = getHighlightStyleIndex(el);
        if (styleIndex === null) return;

        const theme = STYLE_MAP[styleIndex] || STYLE_MAP[0];

        el.setAttribute('style', [
            `background-color:${theme.bg} !important`,
            `background:${theme.bg} !important`,
            `color:${theme.fg} !important`,
            `font-weight:${theme.weight} !important`,
            'display:inline !important',
            'padding:2px 5px !important',
            'border-radius:4px !important',
            'box-decoration-break:clone !important',
            '-webkit-box-decoration-break:clone !important',
            `mso-highlight:${theme.bg} !important`
        ].join(';'));
    }

    function replaceInlineCode(code) {
        if (!code || code.closest('pre')) return;

        const span = document.createElement('span');
        span.innerHTML = code.innerHTML;
        span.setAttribute('style', CODE_STYLE);

        code.replaceWith(span);
    }

    function normalizeCopiedHtml(root) {
        if (!root) return;

        if (root.matches && root.matches('[class*="FindManyStrings-style-"]')) {
            applyHighlightStyle(root);
        }

        root.querySelectorAll('[class*="FindManyStrings-style-"]').forEach(applyHighlightStyle);

        if (root.matches && root.matches('code')) {
            replaceInlineCode(root);
        }

        root.querySelectorAll('code').forEach(replaceInlineCode);

        root.querySelectorAll('*').forEach(el => {
            el.removeAttribute('data-onenote-inline-fixed');
            el.removeAttribute('data-onenote-code-fixed');
        });
    }

    function cloneRangeWithStyleContext(range) {
        const fragment = range.cloneContents();

        const startEl = getElement(range.startContainer);
        const endEl = getElement(range.endContainer);

        if (!startEl || !endEl) return fragment;

        const startHighlight = startEl.closest('[class*="FindManyStrings-style-"]');
        const endHighlight = endEl.closest('[class*="FindManyStrings-style-"]');

        if (startHighlight && startHighlight === endHighlight) {
            const wrapper = startHighlight.cloneNode(false);
            wrapper.appendChild(fragment);

            const newFragment = document.createDocumentFragment();
            newFragment.appendChild(wrapper);

            return newFragment;
        }

        const startCode = startEl.closest('code');
        const endCode = endEl.closest('code');

        if (startCode && startCode === endCode && !startCode.closest('pre')) {
            const wrapper = startCode.cloneNode(false);
            wrapper.appendChild(fragment);

            const newFragment = document.createDocumentFragment();
            newFragment.appendChild(wrapper);

            return newFragment;
        }

        return fragment;
    }

    function buildOfficeFriendlyHtml(innerHtml) {
        return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
    font-family: Calibri, Arial, sans-serif;
    font-size: 11pt;
}
</style>
</head>
<body>
${innerHtml}
</body>
</html>`.trim();
    }

    function handleCopy(e) {
        if (e.__onenoteHighlightHandled) return;

        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return;

        const plainText = selection.toString();
        if (!plainText || plainText.trim() === '') return;

        const container = document.createElement('div');

        for (let i = 0; i < selection.rangeCount; i++) {
            const range = selection.getRangeAt(i);
            const fragment = cloneRangeWithStyleContext(range);
            container.appendChild(fragment);
        }

        normalizeCopiedHtml(container);

        const cleanedHtml = container.innerHTML.trim();
        if (!cleanedHtml) return;

        const fullHtml = buildOfficeFriendlyHtml(cleanedHtml);

        try {
            e.__onenoteHighlightHandled = true;

            e.clipboardData.setData('text/html', fullHtml);
            e.clipboardData.setData('text/plain', plainText);

            e.preventDefault();
            e.stopImmediatePropagation();
        } catch (err) {
            console.warn('[OneNote Highlight Copy] clipboard write failed:', err);
        }
    }

    function injectPreviewCss() {
        if (!document.documentElement) return;
        if (document.getElementById('onenote-highlight-copy-css')) return;

        const style = document.createElement('style');
        style.id = 'onenote-highlight-copy-css';

        style.textContent = `
[class*="FindManyStrings-style-0"] {
    background-color: #ffff00 !important;
    background: #ffff00 !important;
    color: #000000 !important;
    font-weight: 700 !important;
    display: inline !important;
    padding: 2px 5px !important;
    border-radius: 4px !important;
}

[class*="FindManyStrings-style-1"] {
    background-color: #ffc400 !important;
    background: #ffc400 !important;
    color: #000000 !important;
    font-weight: 700 !important;
    display: inline !important;
    padding: 2px 5px !important;
    border-radius: 4px !important;
}

[class*="FindManyStrings-style-2"] {
    background-color: #ff0000 !important;
    background: #ff0000 !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    display: inline !important;
    padding: 2px 5px !important;
    border-radius: 4px !important;
}

[class*="FindManyStrings-style-3"] {
    background-color: #3f8cff !important;
    background: #3f8cff !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    display: inline !important;
    padding: 2px 5px !important;
    border-radius: 4px !important;
}

code:not(pre code) {
    color: #df38dd !important;
    background-color: #f3f3f3 !important;
    background: #f3f3f3 !important;
    font-family: Consolas, Monaco, monospace !important;
    padding: 2px 5px !important;
    border-radius: 3px !important;
    font-size: 0.9em !important;
}
        `;

        const target = document.head || document.documentElement;
        target.appendChild(style);
    }

    function init() {
        injectPreviewCss();

        window.removeEventListener('copy', handleCopy, true);
        document.removeEventListener('copy', handleCopy, true);

        window.addEventListener('copy', handleCopy, true);
        document.addEventListener('copy', handleCopy, true);
    }

    init();

    document.addEventListener('DOMContentLoaded', init, true);

    let retryCount = 0;
    const timer = setInterval(() => {
        injectPreviewCss();
        retryCount++;

        if (retryCount > 20) {
            clearInterval(timer);
        }
    }, 500);

})();

预览效果 ![[Pasted image 20260517010021.png|300]]

你的思路是对的:复制时把 FindManyStrings 的 class 样式转换成内联 style,因为 OneNote 基本不会识别网页里的外部 CSS / class。

但你这版有一个关键问题: 当你只选中高亮 span 里面的一部分文字时,range.cloneContents() 很可能只克隆出纯文本,不会带上外层 span.FindManyStrings-style-x,所以 OneNote 收到的 HTML 里根本没有高亮样式。

可以直接把脚本改成下面这个版本。重点修复了:

  1. 复制局部高亮文字时,自动补回外层高亮 span。
  2. 复制局部行内代码时,自动补回代码样式。
  3. 给 OneNote 更友好的完整 HTML。
  4. 不再直接替换网页里的 <code>,避免破坏 Gemini / 聚合站页面结构。
// ==UserScript==
// @name         Gemini & NiceAIGC Highlight Copy to OneNote Fixed
// @namespace    http://tampermonkey.net/
// @version      5.1
// @description  修复 Gemini / NiceAIGC 中 FindManyStrings 高亮和行内代码复制到 OneNote 丢样式的问题
// @match        https://gemini.google.com/*
// @match        https://*.nice188.com/*
// @match        *://*/*
// @include      about:blank
// @include      about:srcdoc
// @grant        none
// @run-at       document-end
// @allFrames    true
// ==/UserScript==

(function () {
    'use strict';

    const STYLE_MAP = {
        0: { bg: '#ffff00', fg: '#000000', weight: '700' },
        1: { bg: '#ffc400', fg: '#000000', weight: '700' },
        2: { bg: '#ff0000', fg: '#ffffff', weight: '700' },
        3: { bg: '#3f8cff', fg: '#ffffff', weight: '700' }
    };

    const CODE_STYLE = [
        'color:#df38dd !important',
        'background-color:#f3f3f3 !important',
        'background:#f3f3f3 !important',
        'font-family:Consolas, Monaco, monospace !important',
        'padding:2px 5px !important',
        'border-radius:3px !important',
        'font-size:0.9em !important',
        'display:inline !important',
        'white-space:pre-wrap !important'
    ].join(';');

    function getElement(node) {
        if (!node) return null;
        return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
    }

    function getHighlightStyleIndex(el) {
        if (!el) return null;
        const className = String(el.className || '');
        const match = className.match(/FindManyStrings-style-(\d+)/);
        return match ? Number(match[1]) : null;
    }

    function applyHighlightStyle(el) {
        const styleIndex = getHighlightStyleIndex(el);
        if (styleIndex === null) return;

        const theme = STYLE_MAP[styleIndex] || STYLE_MAP[0];

        el.setAttribute('style', [
            `background-color:${theme.bg} !important`,
            `background:${theme.bg} !important`,
            `color:${theme.fg} !important`,
            `font-weight:${theme.weight} !important`,
            'display:inline !important',
            'padding:2px 5px !important',
            'border-radius:4px !important',
            'box-decoration-break:clone !important',
            '-webkit-box-decoration-break:clone !important',
            `mso-highlight:${theme.bg} !important`
        ].join(';'));
    }

    function replaceInlineCode(code) {
        if (!code || code.closest('pre')) return;

        const span = document.createElement('span');
        span.innerHTML = code.innerHTML;
        span.setAttribute('style', CODE_STYLE);
        code.replaceWith(span);
    }

    function normalizeCopiedHtml(root) {
        if (!root) return;

        root.querySelectorAll('[class*="FindManyStrings-style-"]').forEach(applyHighlightStyle);

        if (root.matches && root.matches('[class*="FindManyStrings-style-"]')) {
            applyHighlightStyle(root);
        }

        root.querySelectorAll('code').forEach(replaceInlineCode);

        if (root.matches && root.matches('code')) {
            replaceInlineCode(root);
        }
    }

    // 关键修复:当只选中高亮 span 或 code 里面的一部分文字时,cloneContents 可能只返回纯文本。
    // 这里把外层高亮 span/code 补回来。
    function cloneRangeWithStyleContext(range) {
        const fragment = range.cloneContents();

        const startEl = getElement(range.startContainer);
        const endEl = getElement(range.endContainer);

        if (!startEl || !endEl) return fragment;

        const highlightEl = startEl.closest('[class*="FindManyStrings-style-"]');
        if (highlightEl && highlightEl.contains(endEl)) {
            const wrapper = highlightEl.cloneNode(false);
            wrapper.appendChild(fragment);
            const newFragment = document.createDocumentFragment();
            newFragment.appendChild(wrapper);
            return newFragment;
        }

        const codeEl = startEl.closest('code');
        if (codeEl && codeEl.contains(endEl) && !codeEl.closest('pre')) {
            const wrapper = codeEl.cloneNode(false);
            wrapper.appendChild(fragment);
            const newFragment = document.createDocumentFragment();
            newFragment.appendChild(wrapper);
            return newFragment;
        }

        return fragment;
    }

    // 页面显示层:只注入 CSS,不直接替换 Gemini / NiceAIGC 的 DOM
    function injectPreviewCss() {
        if (document.getElementById('onenote-highlight-copy-css')) return;

        const style = document.createElement('style');
        style.id = 'onenote-highlight-copy-css';

        style.textContent = `
            [class*="FindManyStrings-style-0"] {
                background-color: #ffff00 !important;
                color: #000000 !important;
                font-weight: 700 !important;
                display: inline !important;
                padding: 2px 5px !important;
                border-radius: 4px !important;
            }

            [class*="FindManyStrings-style-1"] {
                background-color: #ffc400 !important;
                color: #000000 !important;
                font-weight: 700 !important;
                display: inline !important;
                padding: 2px 5px !important;
                border-radius: 4px !important;
            }

            [class*="FindManyStrings-style-2"] {
                background-color: #ff0000 !important;
                color: #ffffff !important;
                font-weight: 700 !important;
                display: inline !important;
                padding: 2px 5px !important;
                border-radius: 4px !important;
            }

            [class*="FindManyStrings-style-3"] {
                background-color: #3f8cff !important;
                color: #ffffff !important;
                font-weight: 700 !important;
                display: inline !important;
                padding: 2px 5px !important;
                border-radius: 4px !important;
            }

            code:not(pre code) {
                color: #df38dd !important;
                background-color: #f3f3f3 !important;
                font-family: Consolas, Monaco, monospace !important;
                padding: 2px 5px !important;
                border-radius: 3px !important;
                font-size: 0.9em !important;
            }
        `;

        (document.head || document.documentElement).appendChild(style);
    }

    function handleCopy(e) {
        if (e.__onenoteHighlightHandled) return;

        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return;

        const plainText = selection.toString();
        if (!plainText || plainText.trim() === '') return;

        const container = document.createElement('div');

        for (let i = 0; i < selection.rangeCount; i++) {
            const range = selection.getRangeAt(i);
            const fragment = cloneRangeWithStyleContext(range);
            container.appendChild(fragment);
        }

        normalizeCopiedHtml(container);

        if (!container.innerHTML.trim()) return;

        const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
${container.innerHTML}
</body>
</html>`.trim();

        try {
            e.__onenoteHighlightHandled = true;

            e.clipboardData.setData('text/html', html);
            e.clipboardData.setData('text/plain', plainText);

            e.preventDefault();
            e.stopImmediatePropagation();
        } catch (err) {
            // 如果某些沙箱环境禁止写 clipboardData,就交还给浏览器默认复制
        }
    }

    injectPreviewCss();

    // document + window 双层捕获,尽量抢在 Gemini / NiceAIGC 自己的复制逻辑之前
    document.addEventListener('copy', handleCopy, true);
    window.addEventListener('copy', handleCopy, true);
})();

最关键的修复点是这个函数:

cloneRangeWithStyleContext(range)

因为你原来的逻辑在这种情况下会失效:

<span class="FindManyStrings-style-0">重要内容</span>

如果你只选中“重要”两个字,range.cloneContents() 很可能只得到:

重要

而不是:

<span class="FindManyStrings-style-0">重要</span>

OneNote 收到纯文本,自然不会保留高亮。

另外,建议你测试时用这三种方式分别复制:

  1. 整段复制。
  2. 只复制某个高亮词的一部分。
  3. 从高亮文字前面开始,跨过高亮文字,再复制到普通文字后面。

如果这三种都能进 OneNote 保留颜色,基本就稳定了。

Source: node5.nice188.com

gemini 输出结果为何了视觉美化 样式美化调整使用 sytlebot 美化后对比预览 ![[Pasted image 20260502164336.png|1000]]

另外为快速锁定关键词,用 multi words highlight 高亮关键词 ![[Pasted image 20260502164530.png|800]]

阅读后,觉得有价值,有时候还需要保持高亮样式,粘贴到 OneNote 问题是gemini 回答输出 粘贴后,能保持 stylebot的部分样式,但是无法保持 multi words highlight的样式。 如图 ![[Pasted image 20260502164721.png|1000]] 解决方案 第一步:允许复制+插件, 解除右键 复制粘贴 限制插件破解 gemini 本身 js保护 ![[Pasted image 20260502164849.png]] 第二步:用 篡改猴 油猴制作一个脚本,代码如下

// ==UserScript==
// @name         Gemini Multi Words Highlight to OneNote
// @namespace    http://tampermonkey.net/
// @version      3.0
// @description  让 Gemini 页面里的 FindManyStrings 多词高亮复制到 OneNote 时保留颜色
// @match        https://gemini.google.com/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function () {
    'use strict';
    const STYLE_MAP = {
        0: {
            backgroundColor: '#ffff00',
            color: '#000000',
            fontWeight: '700',
            padding: '1px 5px',
            borderRadius: '4px',
            boxShadow: '0 1px 4px rgba(0,0,0,.25)'
        },
        1: {
            backgroundColor: '#ffc400',
            color: '#000000',
            fontWeight: '700',
            padding: '1px 5px',
            borderRadius: '4px',
            boxShadow: '0 1px 4px rgba(0,0,0,.25)'
        },
        2: {
            backgroundColor: '#ff0000',
            color: '#ffffff',
            fontWeight: '700',
            padding: '1px 5px',
            borderRadius: '4px',
            boxShadow: '0 1px 4px rgba(0,0,0,.25)'
        },
        3: {
            backgroundColor: '#3f8cff',
            color: '#ffffff',
            fontWeight: '700',
            padding: '1px 5px',
            borderRadius: '4px',
            boxShadow: '0 1px 4px rgba(0,0,0,.25)'
        }
    };

    function applyInlineHighlight(root = document) {
        const spans = root.querySelectorAll(
            'span[class*="chrome-extension-FindManyStrings-style-"]'
        );

        spans.forEach(span => {
            if (span.dataset.onenoteInlineFixed === '1') return;

            const className = span.className;
            const match = className.match(/chrome-extension-FindManyStrings-style-(\d+)/);
            if (!match) return;

            const styleIndex = Number(match[1]);
            const style = STYLE_MAP[styleIndex] || STYLE_MAP[0];

            Object.assign(span.style, style);

            span.style.display = 'inline';
            span.style.lineHeight = '1.4';
            span.style.textDecoration = 'none';

            span.dataset.onenoteInlineFixed = '1';
        });
    }

    function convertCodeToSpan(root = document) {
        const codes = root.querySelectorAll('code');
        codes.forEach(code => {
            if (code.dataset.onenoteCodeFixed === '1') return;
            const span = document.createElement('span');
            span.innerHTML = code.innerHTML;
            span.style.color = '#df38dd';
            span.style.backgroundColor = '#f3f3f3';
            span.style.fontFamily = 'Consolas, Monaco, monospace';
            span.style.padding = '2px 5px';
            span.style.borderRadius = '3px';
            span.style.fontSize = '0.9em';
            span.dataset.onenoteCodeFixed = '1';
            code.replaceWith(span);
        });
    }

    function fixAll() {
        applyInlineHighlight();
        convertCodeToSpan();
    }
    // 页面动态生成时持续修正
    const observer = new MutationObserver(() => fixAll());
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
    setInterval(fixAll, 1000);
    fixAll();
    // 复制时再次强制处理选区 HTML
    document.addEventListener('copy', function (e) {
        const selection = window.getSelection();
        if (!selection || selection.rangeCount === 0) return;
        const container = document.createElement('div');
        for (let i = 0; i < selection.rangeCount; i++) {
            container.appendChild(selection.getRangeAt(i).cloneContents());
        }
        applyInlineHighlight(container);
        convertCodeToSpan(container);
        e.clipboardData.setData('text/html', container.innerHTML);
        e.clipboardData.setData('text/plain', container.innerText);
        e.preventDefault();
    });
})();

也就是 四个插件,实现美化,粘贴OneNote 高亮单词依旧保持样式,结果对比 最后结果截图 ![[Pasted image 20260502165226.png|1000]]