I updated the code a little to only scrape the H2s of the post and I found a way to automatically insert the links - if you copy the result to google docs or notion and then copy that result into substack it adds the links automatically. It's not perfect but it's working :)
Awesome post! Saves me a butt ton of time.
I updated the code a little to only scrape the H2s of the post and I found a way to automatically insert the links - if you copy the result to google docs or notion and then copy that result into substack it adds the links automatically. It's not perfect but it's working :)
function getAllH2HeadingLinks() {
return Array.from(document.querySelectorAll('.header-with-anchor-widget'))
.filter(h => h.tagName === 'H2'); // Filter for H2 headings only
}
let formattedTable = ``;
const headingLinks = getAllH2HeadingLinks();
for (const headingLink of headingLinks) {
const headingHref = headingLink.querySelector('.header-anchor-widget-button').getAttribute("href");
const headingText = headingLink.innerText.trim();
// Formatting as Markdown links
formattedTable += `- [${headingText}](${headingHref})\n`;
}
function copyTableOfContents() {
return new Promise((resolve, reject) => {
const asyncCopyToClipboard = async () => {
try {
await navigator.clipboard.writeText(formattedTable.trim());
resolve(`successfully copied to clipboard`);
} catch (e) {
reject(e);
}
window.removeEventListener("focus", asyncCopyToClipboard);
};
window.addEventListener("focus", asyncCopyToClipboard);
console.log("Hit <Tab> or click on your document to give focus back (or the links won't get copied to clipboard);");
});
}
// To call:
copyTableOfContents().then((r) => console.log(r));