mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-18 16:01:40 +03:00
8dfa490638
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.
39 lines
1.1 KiB
JavaScript
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();
|