ChatGPT to Word Exporter

Export each ChatGPT answer as a Word (.docx) file with proper HTML wrapping

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

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

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         ChatGPT to Word Exporter
// @namespace    https://greasyfork.org/
// @version      1.0
// @description  Export each ChatGPT answer as a Word (.docx) file with proper HTML wrapping
// @author       Bui Quoc Dung
// @match        https://chatgpt.com/*
// @grant        none
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/html-docx.min.js
// ==/UserScript==

(function () {
  'use strict';

  function createExportButton(onClick) {
    const btn = document.createElement('button');
    btn.textContent = 'docx';
    btn.style.marginLeft = '6px';
    btn.style.padding = '4px 8px';
    btn.style.border = '1px solid #ccc';
    btn.style.borderRadius = '4px';
    btn.style.cursor = 'pointer';
    btn.addEventListener('click', onClick);
    return btn;
  }


  function exportWord(htmlContent, filename = 'chatgpt-response') {
    const contentWithWrapper = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
${htmlContent}
</body>
</html>`;

    try {
      const fileBlob = window.htmlDocx.asBlob(contentWithWrapper); // đúng API html-docx-js

      const link = document.createElement('a');
      link.href = URL.createObjectURL(fileBlob);
      link.download = filename + '.docx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('Error exporting to Word:', error);
    }
  }

  function injectExportButtons() {
    const answers = document.querySelectorAll('[data-message-author-role="assistant"]');

    answers.forEach((answer, index) => {
      if (answer.querySelector('.export-chatgpt-button')) return;

      const markdown = answer.querySelector('.markdown');
      if (!markdown) return;

      const container = document.createElement('div');
      container.className = 'export-chatgpt-button';
      container.style.marginTop = '8px';

      const exportBtn = createExportButton(() => {
        exportWord(markdown.innerHTML, `chatgpt-response-${index + 1}`);
      });

      container.appendChild(exportBtn);
      answer.appendChild(container);
    });
  }


  const observer = new MutationObserver(injectExportButtons);
  observer.observe(document.body, { childList: true, subtree: true });


  injectExportButtons();
})();