Skip to content

Instantly share code, notes, and snippets.

@takatama
Last active June 8, 2023 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatama/a8726d690dfdc8c84e8e878c93d4b1a1 to your computer and use it in GitHub Desktop.
Save takatama/a8726d690dfdc8c84e8e878c93d4b1a1 to your computer and use it in GitHub Desktop.
ChatGPT conversation to markdown bookmarklet
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 talks = [...document.querySelectorAll('.text-base')];
const title = talks.length % 2 === 0 ? '' : sanitize(`# ${talks.shift().innerText}\n\n`);
const text = talks.map((talk, i) => {
const who = i % 2 === 0 ? 'You' : 'ChatGPT';
const elements = talk.querySelectorAll('p,ol,ul,pre,table');
const c = elements.length === 0 ? talk.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;">${title}${sanitize(text)}</pre></body>`);
w.document.close();
})();
@takatama
Copy link
Author

takatama commented Mar 30, 2023

This bookmarklet converts conversations with ChatGPT in OpenAI's chat application to Markdown format and displays them in a new window.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment