DEV: Update Twitter meta tags while navigating in app (#19468)

We update `og:title`, `og:url`, might as well update `twitter:title`
and `twitter:url`. This might also fix a Chrome/Android issue where the
root URL is shared instead of the current page's URL.
This commit is contained in:
Penar Musaraj 2022-12-14 14:33:09 -05:00 committed by GitHub
parent f01ecd1fb7
commit b1b8a7ebfe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 6 deletions

View File

@ -8,8 +8,12 @@ export default {
// seems it has started using opengraph tags when sharing
const ogTitle = document.querySelector("meta[property='og:title']");
const ogUrl = document.querySelector("meta[property='og:url']");
const twitterTitle = document.querySelector(
"meta[property='twitter:title']"
);
const twitterUrl = document.querySelector("meta[property='twitter:url']");
if (!ogTitle || !ogUrl) {
if (!ogTitle || !ogUrl || !twitterTitle || !twitterUrl) {
return;
}
@ -17,6 +21,8 @@ export default {
appEvents.on("page:changed", ({ title, url }) => {
ogTitle.setAttribute("content", title);
ogUrl.setAttribute("content", getAbsoluteURL(url));
twitterTitle.setAttribute("content", title);
twitterUrl.setAttribute("content", getAbsoluteURL(url));
});
},
};

View File

@ -8,14 +8,10 @@ acceptance("Opengraph Tag Updater", function (needs) {
return helper.response({});
});
});
needs.settings({
navigation_menu: "legacy",
});
test("updates OG title and URL", async function (assert) {
await visit("/");
await click("#toggle-hamburger-menu");
await click("a.about-link");
await click("a[href='/about']");
assert.strictEqual(
document
@ -31,5 +27,19 @@ acceptance("Opengraph Tag Updater", function (needs) {
.endsWith("/about"),
"it should update OG URL"
);
assert.strictEqual(
document
.querySelector("meta[property='twitter:title']")
.getAttribute("content"),
document.title,
"it should update OG title"
);
assert.ok(
document
.querySelector("meta[property='twitter:url']")
.getAttribute("content")
.endsWith("/about"),
"it should update OG URL"
);
});
});

View File

@ -8,6 +8,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:title" content="Discourse Tests" />
<meta property="og:url" content="{{rootURL}}" />
<meta property="twitter:title" content="Discourse Tests" />
<meta property="twitter:url" content="{{rootURL}}" />
<meta name="color-scheme" content="light dark">
{{content-for "head"}} {{content-for "test-head"}}