diff --git a/app/assets/javascripts/discourse/app/initializers/opengraph-tag-updater.js b/app/assets/javascripts/discourse/app/initializers/opengraph-tag-updater.js new file mode 100644 index 00000000000..66ab52a817f --- /dev/null +++ b/app/assets/javascripts/discourse/app/initializers/opengraph-tag-updater.js @@ -0,0 +1,20 @@ +import { getAbsoluteURL } from "discourse-common/lib/get-url"; + +export default { + name: "opengraph-tag-updater", + + initialize(container) { + // workaround for Safari on iOS 14.3 + // seems it has started using opengraph tags when sharing + let appEvents = container.lookup("service:app-events"); + const ogTitle = document.querySelector("meta[property='og:title']"), + ogUrl = document.querySelector("meta[property='og:url']"); + + if (ogTitle && ogUrl) { + appEvents.on("page:changed", (data) => { + ogTitle.setAttribute("content", data.title); + ogUrl.setAttribute("content", getAbsoluteURL(data.url)); + }); + } + }, +}; diff --git a/app/assets/javascripts/discourse/tests/acceptance/opengraph-tag-updater-test.js b/app/assets/javascripts/discourse/tests/acceptance/opengraph-tag-updater-test.js new file mode 100644 index 00000000000..ab3a72e1e98 --- /dev/null +++ b/app/assets/javascripts/discourse/tests/acceptance/opengraph-tag-updater-test.js @@ -0,0 +1,32 @@ +import { click, visit } from "@ember/test-helpers"; +import { acceptance } from "discourse/tests/helpers/qunit-helpers"; +import { test } from "qunit"; + +acceptance("Opengraph Tag Updater", function (needs) { + needs.pretender((server, helper) => { + server.get("/about", () => { + return helper.response({}); + }); + }); + + test("updates OG title and URL", async function (assert) { + await visit("/"); + await click("#toggle-hamburger-menu"); + await click("a.about-link"); + + assert.equal( + document + .querySelector("meta[property='og:title']") + .getAttribute("content"), + document.title, + "it should update OG title" + ); + assert.ok( + document + .querySelector("meta[property='og:url']") + .getAttribute("content") + .endsWith("/about"), + "it should update OG URL" + ); + }); +}); diff --git a/app/views/qunit/index.html.erb b/app/views/qunit/index.html.erb index eef411cfd57..6109dec2839 100644 --- a/app/views/qunit/index.html.erb +++ b/app/views/qunit/index.html.erb @@ -6,6 +6,8 @@ <%= javascript_include_tag "test_helper" %> <%= csrf_meta_tags %> + +