Ghost/ghost/link-replacer/lib/LinkReplacer.js
Simon Backx 8dfa490638
Added outbound link tagging for web posts (#16201)
fixes https://github.com/TryGhost/Team/issues/2433

- Moved all outbound link tagging code to separate OutboundLinkTagger
- Because a site can easily enable/disable this feature, we don't store
the ?refs in the HTML but add them on the fly for now in the Content
API.
2023-02-16 11:26:35 +01:00

39 lines
1.1 KiB
JavaScript

class LinkReplacer {
/**
* Replaces the links in the provided HTML
* @param {string} html
* @param {(url: URL): Promise<URL|string>} replaceLink
* @returns {Promise<string>}
*/
async replace(html, replaceLink) {
const cheerio = require('cheerio');
try {
const $ = cheerio.load(html);
for (const el of $('a').toArray()) {
const href = $(el).attr('href');
if (href) {
let url;
try {
url = new URL(href);
} catch (e) {
// Ignore invalid URLs
}
if (url) {
url = await replaceLink(url);
const str = url.toString();
$(el).attr('href', str);
}
}
}
return $.html();
} catch (e) {
// Catch errors from cheerio
return html;
}
}
}
module.exports = new LinkReplacer();