ChatGPT to Word Exporter

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

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

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

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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();
})();