Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/@vuepress/core/lib/client/index.ssr.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<meta name="generator" content="VuePress {{ version }}">
{{{ userHeadTags }}}
{{{ pageMeta }}}
{{{ canonicalLink }}}
{{{ renderResourceHints() }}}
{{{ renderStyles() }}}
</head>
Expand Down
29 changes: 29 additions & 0 deletions packages/@vuepress/core/lib/client/root-mixins/updateMeta.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export default {
this.$ssrContext.title = this.$title
this.$ssrContext.lang = this.$lang
this.$ssrContext.pageMeta = renderPageMeta(mergedMetaItems)
this.$ssrContext.canonicalLink = renderCanonicalLink(this.$canonicalUrl)
}
},
// Other life cycles will only be called at client
Expand All @@ -22,6 +23,7 @@ export default {

// update title / meta tags
this.updateMeta()
this.updateCanonicalLink()
},

methods: {
Expand All @@ -39,18 +41,45 @@ export default {
// description needs special attention as it has too many entries
return unionBy([{ name: 'description', content: this.$description }],
pageMeta, this.siteMeta, metaIdentifier)
},

updateCanonicalLink () {
removeCanonicalLink()

if (!this.$canonicalUrl) {
return
}

document.head.insertAdjacentHTML('beforeend', renderCanonicalLink(this.$canonicalUrl))
}
},

watch: {
$page () {
this.updateMeta()
this.updateCanonicalLink()
}
},

beforeDestroy () {
updateMetaTags(null, this.currentMetaTags)
removeCanonicalLink()
}
}

function removeCanonicalLink () {
const canonicalEl = document.querySelector("link[rel='canonical']")

if (canonicalEl) {
canonicalEl.remove()
}
}

function renderCanonicalLink (link = '') {
if (!link) {
return ''
}
return `<link href="${link}" rel="canonical" />`
}

/**
Expand Down
10 changes: 10 additions & 0 deletions packages/@vuepress/core/lib/node/ClientComputedMixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ module.exports = siteData => {
return this.$localeConfig.title || this.$site.title || ''
}

get $canonicalUrl () {
const { canonical } = this.$page.frontmatter

if (typeof canonical === 'string') {
return canonical
}

return false
}

get $title () {
const page = this.$page
const { metaTitle } = this.$page.frontmatter
Expand Down
7 changes: 7 additions & 0 deletions packages/docs/docs/guide/frontmatter.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ meta:
---
```

### canonicalUrl <Badge text="1.7.0+" />

- Type: `string`
- Default: `undefined`

Set the canonical URL for the current page.

## Predefined Variables Powered By Default Theme

### navbar
Expand Down