Skip to content

Commit

Permalink
chore: handle when name = property
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Oct 18, 2024
1 parent 15e8469 commit 5ef84c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/html.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,16 @@ const addBody = ({ url, headers, html }) => {
const rewriteMetaTags = ({ $ }) => {
$('meta').each((_, element) => {
const el = $(element)
// Convert 'name' to 'property' for Open Graph tags
// <meta name="og:title" content="Kiko Beats"> → <meta property="og:title" content="Kiko Beats">
if (el.attr('name')?.startsWith('og:')) {
const name = el.attr('name')

const name = el.attr('name')
const property = el.attr('property')

// Convert 'name' to 'property' for Open Graph tags if 'property' is not already set correctly
if (name?.startsWith('og:') && property !== name) {
el.removeAttr('name').attr('property', name)
debug('og', el.attr())
// Convert 'property' to 'name' for non-Open Graph tags
// <meta property="title" content="Kiko Beats"> → <meta name="title" content="Kiko Beats">
} else if (el.attr('property') && !el.attr('property').startsWith('og')) {
const property = el.attr('property')
} else if (property && !property.startsWith('og')) {
el.removeAttr('property').attr('name', property)
debug('meta', el.attr())
}
Expand Down Expand Up @@ -188,7 +188,7 @@ module.exports = ({

if (rewriteUrls) rewriteHtmlUrls({ $, url })

if (rewriteHtml) rewriteMetaTags({ $ })
if (rewriteHtml) rewriteMetaTags({ $, url })

addHead({ $, url, headers })

Expand Down
21 changes: 21 additions & 0 deletions test/html/rewrite-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,27 @@ const composeHtml = meta =>
<body></body>
</html>`)

test("don't rewrite og if property is already present", async t => {
const output = html({
rewriteHtml: true,
url: 'https://kikobeats.com',
html: composeHtml([
'<meta content="This Pin was discovered by NMA Group" data-app="true" name="og:description" property="og:description">'
]),
headers: { 'content-type': 'text/html; charset=utf-8' }
})

const $ = cheerio.load(output)
t.is(
$('meta[name="og:description"]').attr('content'),
'This Pin was discovered by NMA Group'
)
t.is(
$('meta[property="og:description"]').attr('content'),
'This Pin was discovered by NMA Group'
)
})

test('rewrite multiple og wrong markup', async t => {
const output = html({
rewriteHtml: true,
Expand Down

0 comments on commit 5ef84c4

Please sign in to comment.