LoginSignup
9
3

ChatGPTとの会話をMarkdownに変換するブックマークレット

Last updated at Posted at 2023-03-29

ChatGPTとの会話をMarkdown形式のテキストとして別ウィンドウに表示します。
リスト、ソースコード、表にも対応しました。

javascript:(function() {
  if (!document.URL.startsWith('https://chat.openai.com')) {
    alert('Please use on https://chat.openai.com');
    return;
  }
  const sanitize = html => {
    return String(html).replace(/&/g,'&')
      .replace(/</g,'&lt;')
      .replace(/>/g,'&gt;')
      .replace(/"/g,'&quot;');
  };
  const table = element => {
    const rows = [...element.rows].map(row => [...row.cells].map(cell => cell.innerText));
    const header = rows.shift();
    const separator = header.map(() => '---');
    const body = rows.map(row => `| ${row.join(' | ')} |`);
    return `| ${header.join(' | ')} |\n|${separator.join('|')}|\n${body.join('\n')}`;
  };
  const escapeTags = text => {
    return String(text).replace(/<(\/?[a-zA-Z]+)>/g, '`<$1>`');
  };
 const content = element => {
    const tag = element.tagName;
    if (tag === 'OL') return [...element.querySelectorAll('li')].map((li, i) => `${i+1}. ${li.innerText}`).join('\n');
    if (tag === 'UL') return [...element.querySelectorAll('li')].map(li => `- ${li.innerText}`).join('\n');
    if (tag === 'PRE') {
      const lang = element.querySelector('span').innerText;
      return '```' + lang + '\n' + element.querySelector('code').innerText + '```';
    }
    if (tag === 'TABLE') return table(element);
    return escapeTags(element.innerText);
  };
  const messages = [...document.querySelectorAll('div[data-message-author-role]')];
  const text = messages.map((m, i) => {
    const who = m.getAttribute('data-message-author-role') == 'user' ? 'あなた' : 'ChatGPT';
    const elements = m.querySelectorAll('p,ol,ul,pre,table');
    const c = elements.length === 0 ? m.innerText : [...elements].map(e => content(e)).join('\n\n');
    return `## ${who}:\n${c}`;
  }).join('\n\n');
  const w = window.open('', 'target', 'width=640,height=600');
  w.document.write(`<body><pre style="white-space: pre-wrap;">${sanitize(text)}</pre></body>`);
  w.document.close();
})();

ChatGPTによる説明:

このブックマークレットは、OpenAIのチャットアプリケーションの画面でChatGPTとの会話履歴をMarkdown形式に変換して表示するものです。以下の手順で動作します。

  1. 現在のURLがOpenAIのチャットページであるかどうかを確認します。
  2. sanitize関数を定義し、HTMLのエスケープ処理を行うために使用します。
  3. table関数を定義し、テーブルタグをMarkdown形式のテキストに変換します。
  4. content関数を定義し、各要素をMarkdown形式のテキストに変換します。
  5. .text-baseクラスを持つ要素に対して、ChatGPTとの会話の各部分を取得します。
  6. 取得した各部分をMarkdown形式に変換します。
  7. 変換されたテキストを新しいウィンドウに表示します。

このブックマークレットは、ユーザーがOpenAIのチャットアプリケーションでChatGPTとの過去の会話をMarkdown形式で表示し、コピーや保存などの用途に使用することができます。

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3