|
| 1 | +const gfm = require('turndown-plugin-gfm').gfm; |
| 2 | +const TurndownService = require('turndown').default; |
| 3 | + |
| 4 | +function stripHyphens (str) { |
| 5 | + const regex = /^--- (.+) ---$/; |
| 6 | + return str.replace(regex, (match, p1) => { |
| 7 | + return p1; |
| 8 | + }); |
| 9 | +} |
| 10 | + |
| 11 | +const newDoc = document.createDocumentFragment(); |
| 12 | +const titleElement = document.createElement('h1'); |
| 13 | +newDoc.appendChild(titleElement); |
| 14 | + |
| 15 | +const link = document.createElement('a'); |
| 16 | +link.href = window.location.href; |
| 17 | +link.innerText = window.location.href; |
| 18 | +newDoc.appendChild(link); |
| 19 | + |
| 20 | +const descriptionHeader = document.createElement('h2'); |
| 21 | +descriptionHeader.innerText = 'Description'; |
| 22 | +newDoc.appendChild(descriptionHeader); |
| 23 | + |
| 24 | +const articleElements = document.querySelectorAll('article'); |
| 25 | +const articleElementsLength = articleElements.length; |
| 26 | +for (let index = 0; index < articleElementsLength; ++index) { |
| 27 | + const article = articleElements[index].cloneNode(true); |
| 28 | + const headingElement = article.querySelector('h2'); |
| 29 | + let heading = stripHyphens(headingElement.innerText); |
| 30 | + |
| 31 | + if (index === 0) { |
| 32 | + titleElement.innerText = heading; |
| 33 | + heading = 'Part One'; |
| 34 | + } |
| 35 | + |
| 36 | + const newHeadingElement = document.createElement('h3'); |
| 37 | + newHeadingElement.innerText = heading; |
| 38 | + headingElement.replaceWith(newHeadingElement); |
| 39 | + |
| 40 | + newDoc.appendChild(article); |
| 41 | +} |
| 42 | + |
| 43 | +const turndownService = new TurndownService({ |
| 44 | + headingStyle: 'atx' |
| 45 | +}); |
| 46 | +turndownService.use(gfm); |
| 47 | + |
| 48 | +const markdown = turndownService.turndown(newDoc).concat('\n'); |
| 49 | + |
| 50 | +browser.runtime.sendMessage({ |
| 51 | + action: "saveAs", |
| 52 | + text: markdown, |
| 53 | +}); |
0 commit comments