2020-11-18 18:45:45 +08:00
|
|
|
/* global hexo */
|
|
|
|
|
|
|
|
'use strict'
|
|
|
|
|
2022-09-30 11:40:30 +08:00
|
|
|
hexo.extend.filter.register(
|
|
|
|
'after_post_render',
|
|
|
|
function (data) {
|
|
|
|
const config = this.config
|
|
|
|
const url = new URL(config.url)
|
|
|
|
const siteHost = url.hostname || config.url
|
2020-11-18 18:45:45 +08:00
|
|
|
|
|
|
|
// Match 'a' tags that don't contain html children.
|
|
|
|
const regPureATag = /<a([^>]*)href="([^"]*)"([^>]*)>([^<]*)<\/a>/gim
|
|
|
|
|
2022-09-30 11:40:30 +08:00
|
|
|
data.content = data.content.replace(
|
|
|
|
regPureATag,
|
|
|
|
function (match, attrBegin, href, attrEnd, html) {
|
|
|
|
// Exit if the href attribute doesn't exists.
|
|
|
|
if (!href) return match
|
2020-11-18 18:45:45 +08:00
|
|
|
|
2022-09-30 11:40:30 +08:00
|
|
|
let link = ''
|
|
|
|
try {
|
|
|
|
link = new URL(href)
|
|
|
|
} catch (e) {
|
|
|
|
// Invalid url, e.g. Anchor link.
|
|
|
|
return match
|
|
|
|
}
|
2020-11-18 18:45:45 +08:00
|
|
|
|
2022-09-30 11:40:30 +08:00
|
|
|
// Exit if the url has same host with `config.url`, which means isn't an external link.
|
|
|
|
if (!link.protocol || link.hostname === siteHost) return match
|
2020-11-18 18:45:45 +08:00
|
|
|
|
2022-09-30 11:40:30 +08:00
|
|
|
return `<a class="link" ${attrBegin} href="${href}" ${attrEnd}>${html}<i class="fas fa-external-link-alt"></i></a>`
|
|
|
|
}
|
|
|
|
)
|
2020-11-18 18:45:45 +08:00
|
|
|
},
|
|
|
|
0
|
|
|
|
)
|