Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Full Ember app embed mode for blog comments (#36613)

Rafael dos Santos Silva3893e55bd5d9
diff --git a/app/assets/stylesheets/common/base/_index.scss b/app/assets/stylesheets/common/base/_index.scss
index ca2020e3157..2f0ea55790a 100644
--- a/app/assets/stylesheets/common/base/_index.scss
+++ b/app/assets/stylesheets/common/base/_index.scss
@@ -69,5 +69,6 @@
@import "user";
@import "user-badges";
@import "user-tips";
+@import "embed-mode";
@import "uc-dismiss";
@import "uc-modernize-foundation-theme";
diff --git a/app/assets/stylesheets/common/base/embed-mode.scss b/app/assets/stylesheets/common/base/embed-mode.scss
new file mode 100644
index 00000000000..e29f2efe58e
--- /dev/null
+++ b/app/assets/stylesheets/common/base/embed-mode.scss
@@ -0,0 +1,20 @@
+// Styles for the full Ember app when rendered in embed mode (iframe)
+// Activated when ?embed_mode=true is in the URL
+body.embed-mode {
+ // Remove top padding since header is hidden
+ #main-outlet {
+ padding-top: 1em;
+ }
+
+ // Hide elements that don't make sense in embed context
+ .signup-cta,
+ .suggested-topics,
+ .more-topics__container {
+ display: none;
+ }
+
+ // Ensure content fills the width
+ #main-outlet-wrapper {
+ max-width: 100%;
+ }
+}
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index e6fed880841..7d0ee9d719c 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -53,6 +53,7 @@ class ApplicationController < ActionController::Base
after_action :add_readonly_header
after_action :perform_refresh_session
after_action :conditionally_allow_site_embedding
+
after_action :ensure_vary_header
after_action :add_noindex_header,
if: -> { is_feed_request? || !SiteSetting.allow_index_in_robots_txt }
diff --git a/app/controllers/embed_controller.rb b/app/controllers/embed_controller.rb
index 0f6e4925661..d58f26160ce 100644
--- a/app/controllers/embed_controller.rb
+++ b/app/controllers/embed_controller.rb
@@ -91,6 +91,14 @@ class EmbedController < ApplicationController
end
response.headers["X-Robots-Tag"] = "noindex, indexifembedded"
+
+ if SiteSetting.embed_full_app && params[:full_app].present? && topic_id
+ topic = Topic.find_by(id: topic_id)
+ raise Discourse::NotFound if topic.blank? || !guardian.can_see?(topic)
+ redirect_to "#{topic.url}?embed_mode=true"
+ return
+ end
+
if topic_id
@topic_view =
TopicView.new(
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb
index 41bbef04e94..471a5011648 100644
--- a/app/controllers/topics_controller.rb
+++ b/app/controllers/topics_controller.rb
@@ -34,6 +34,7 @@ class TopicsController < ApplicationController
]
before_action :consider_user_for_promotion, only: :show
+ after_action :allow_embed_mode, only: :show
skip_before_action :check_xhr, only: %i[show feed]
@@ -1275,6 +1276,14 @@ class TopicsController < ApplicationController
private
+ def allow_embed_mode
+ return if params[:embed_mode].blank?
+ return unless SiteSetting.embed_full_app
+ return unless SiteSetting.embed_any_origin? || EmbeddableHost.record_for_url(request.referer)
+
+ response.headers.delete("X-Frame-Options")
+ end
+
def topic_params
params.permit(:topic_id, :topic_time, timings: {})
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index dfd39547813..281ea3d90b3 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -667,6 +667,11 @@ en:
one: "+%{count} other draft"
other: "+%{count} other drafts"
+ embed_mode:
+ storage_access_prompt: "Already have a %{site_name} account? Allow access to your session to comment as yourself."
+ allow_access: "Allow Access"
+ continue_as_guest: "Continue as Guest"
+
topic_count_all:
one: "See %{count} new topic"
other: "See %{count} new topics"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index f0a6ab09d62..f3ca7947550 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -3171,6 +3171,9 @@ navigation:
area: "navigation"
embedding:
+ embed_full_app:
+ default: false
+ hidden: true
embed_by_username:
default: ""
type: username
diff --git a/frontend/discourse/app/controllers/application.js b/frontend/discourse/app/controllers/application.js
index 94b44af739f..697c43388d5 100644
--- a/frontend/discourse/app/controllers/application.js
+++ b/frontend/discourse/app/controllers/application.js
@@ -7,6 +7,7 @@ import runAfterFramePaint from "discourse/lib/after-frame-paint";
import discourseDebounce from "discourse/lib/debounce";
import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
+import EmbedMode from "discourse/lib/embed-mode";
import { isTesting } from "discourse/lib/environment";
const HIDE_SIDEBAR_KEY = "sidebar-hidden";
@@ -24,8 +25,7 @@ export default class ApplicationController extends Controller {
sidebarDisabledRouteOverride = false;
navigationMenuQueryParamOverride = null;
- showSiteHeader = true;
-
+ _showSiteHeader = true;
@tracked _showSidebar;
get upcomingChangeBodyClasses() {
@@ -44,6 +44,17 @@ export default class ApplicationController extends Controller {
return classes.join(" ");
}
+ get showSiteHeader() {
+ if (EmbedMode.enabled) {
+ return false;
+ }
+ return this._showSiteHeader;
+ }
+
+ set showSiteHeader(value) {
+ this._showSiteHeader = value;
+ }
+
// Some themes may need to override the default value provided by `calculateShowSidebar` using viewport properties.
// Accessing the value in a getter prevents static viewport initialization warnings.
get showSidebar() {
@@ -107,6 +118,10 @@ export default class ApplicationController extends Controller {
}
get sidebarEnabled() {
+ if (EmbedMode.enabled) {
+ return false;
+ }
+
if (!this.canDisplaySidebar) {
return false;
}
diff --git a/frontend/discourse/app/instance-initializers/embed-storage-access.js b/frontend/discourse/app/instance-initializers/embed-storage-access.js
new file mode 100644
index 00000000000..8c15afe117e
--- /dev/null
+++ b/frontend/discourse/app/instance-initializers/embed-storage-access.js
@@ -0,0 +1,66 @@
+import EmbedMode from "discourse/lib/embed-mode";
+import { i18n } from "discourse-i18n";
+
+export default {
+ after: "inject-objects",
+
+ initialize(owner) {
+ if (!EmbedMode.enabled) {
+ return;
+ }
+
+ const capabilities = owner.lookup("service:capabilities");
+
+ // Storage Access API is needed for Safari's ITP (Intelligent Tracking Prevention)
+ // which blocks third-party cookies in iframes. Other browsers don't need this.
+ if (!capabilities.isSafari) {
+ return;
+ }
+
+ if (!document.hasStorageAccess || !document.requestStorageAccess) {
+ return;
+ }
+
+ const currentUser = owner.lookup("service:current-user");
+
+ // If user is already logged in, storage access is working
+ if (currentUser) {
+ return;
+ }
+
+ // Check if we have storage access
+ document.hasStorageAccess().then((hasAccess) => {
+ if (hasAccess) {
+ // We have storage access but no user - they're genuinely not logged in
+ return;
+ }
+
+ // Show a prompt to request storage access
+ this.showStorageAccessPrompt(owner);
+ });
+ },
+
+ async showStorageAccessPrompt(owner) {
+ const dialog = owner.lookup("service:dialog");
+ const siteSettings = owner.lookup("service:site-settings");
+ const siteName = siteSettings.title || "this forum";
+
+ const confirmed = await dialog.confirm({
+ message: i18n("embed_mode.storage_access_prompt", {
+ site_name: siteName,
+ }),
+ confirmButtonLabel: "embed_mode.allow_access",
+ cancelButtonLabel: "embed_mode.continue_as_guest",
+ });
+
+ if (confirmed) {
+ try {
+ await document.requestStorageAccess();
+ // Reload to get the session cookie
+ window.location.reload();
+ } catch {
+ // User denied or browser blocked - silently continue as guest
+ }
+ }
+ },
+};
diff --git a/frontend/discourse/app/lib/embed-mode.js b/frontend/discourse/app/lib/embed-mode.js
new file mode 100644
index 00000000000..87a1160f2fd
--- /dev/null
+++ b/frontend/discourse/app/lib/embed-mode.js
@@ -0,0 +1,19 @@
+// Utility for detecting and managing embed mode.
+// When embed_mode=true is in the URL, Discourse renders in a minimal mode
+// suitable for embedding in an iframe on external sites.
+const EmbedMode = {
+ enabled: false,
+
+ init() {
+ const params = new URLSearchParams(window.location.search);
+ this.enabled = params.get("embed_mode") === "true";
+
+ if (this.enabled) {
+ document.body.classList.add("embed-mode");
+ }
+ },
+};
+
+EmbedMode.init();
+
+export default EmbedMode;
diff --git a/frontend/discourse/app/lib/intercept-click.js b/frontend/discourse/app/lib/intercept-click.js
index d8fb98af66b..393c02730ff 100644
--- a/frontend/discourse/app/lib/intercept-click.js
+++ b/frontend/discourse/app/lib/intercept-click.js
@@ -26,7 +26,11 @@ export default function interceptClick(e) {
return;
}
- if (wantsNewWindow(e, target) || target.target === "_blank") {
+ if (target.target === "_blank") {
+ return;
+ }
+
+ if (wantsNewWindow(e)) {
return;
}
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index 9122c517318..d6d2090b3e5 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -4,6 +4,7 @@ import { setOwner } from "@ember/owner";
import { next, schedule } from "@ember/runloop";
import { isEmpty } from "@ember/utils";
import $ from "jquery";
+import EmbedMode from "discourse/lib/embed-mode";
import { isTesting } from "discourse/lib/environment";
import getURL, { withoutPrefix } from "discourse/lib/get-url";
import LockOn from "discourse/lib/lock-on";
@@ -210,6 +211,23 @@ class DiscourseURL extends EmberObject {
return;
}
+ // In embed mode, open all navigation in new tabs except same-topic navigation
+ if (EmbedMode.enabled) {
+ const currentTopicMatch = TOPIC_URL_REGEXP.exec(window.location.pathname);
+ const currentTopicId = currentTopicMatch ? currentTopicMatch[2] : null;
+ const newTopicMatch = TOPIC_URL_REGEXP.exec(path);
+ const newTopicId = newTopicMatch ? newTopicMatch[2] : null;
+
+ // Allow same-topic navigation (scrolling to different posts)
+ if (currentTopicId && newTopicId && currentTopicId === newTopicId) {
+ // Continue with normal routing for same-topic navigation
+ } else {
+ // Open in new tab for all other navigation
+ window.open(getURL(path), "_blank");
+ return;
+ }
+ }
+
if (Session.currentProp("requiresRefresh") && !this.isComposerOpen) {
return this.redirectTo(path);
}
diff --git a/frontend/discourse/app/routes/application.js b/frontend/discourse/app/routes/application.js
index 632ea411555..3eec2ef00b3 100644
--- a/frontend/discourse/app/routes/application.js
+++ b/frontend/discourse/app/routes/application.js
@@ -5,6 +5,7 @@ import NotActivatedModal from "discourse/components/modal/not-activated";
import { RouteException } from "discourse/controllers/exception";
import { setting } from "discourse/lib/computed";
import deprecated from "discourse/lib/deprecated";
+import EmbedMode from "discourse/lib/embed-mode";
import getURL from "discourse/lib/get-url";
import logout from "discourse/lib/logout";
import mobile from "discourse/lib/mobile";
@@ -170,6 +171,11 @@ export default class ApplicationRoute extends DiscourseRoute {
@action
showLogin(props = {}) {
+ if (EmbedMode.enabled) {
+ window.open(getURL("/login"), "_blank");
+ return;
+ }
+
const t = this.router.transitionTo("login");
t.wantsTo = true;
return t.then(() =>
@@ -181,6 +187,11 @@ export default class ApplicationRoute extends DiscourseRoute {
@action
showCreateAccount(props = {}) {
+ if (EmbedMode.enabled) {
+ window.open(getURL("/signup"), "_blank");
+ return;
+ }
+
const t = this.router.transitionTo("signup");
t.wantsTo = true;
return t.then(() =>
diff --git a/frontend/discourse/app/services/capabilities.js b/frontend/discourse/app/services/capabilities.js
index 095eeac2604..7e2cdc9f256 100644
--- a/frontend/discourse/app/services/capabilities.js
+++ b/frontend/discourse/app/services/capabilities.js
@@ -26,10 +26,15 @@ class Capabilities {
isOpera = !!window.opera || ua.includes(" OPR/");
isFirefox = ua.includes("Firefox");
isChrome = !!window.chrome && !this.isOpera;
+ // In iframes, Safari-specific objects aren't accessible, so fall back to UA detection
isSafari =
- /Constructor/.test(window.HTMLElement) ||
- window.safari?.pushNotification?.toString() ===
- "[object SafariRemoteNotification]";
+ window.self !== window.top
+ ? ua.includes("Safari") &&
+ !ua.includes("Chrome") &&
+ !ua.includes("Chromium")
+ : /Constructor/.test(window.HTMLElement) ||
+ window.safari?.pushNotification?.toString() ===
+ "[object SafariRemoteNotification]";
hasContactPicker = "contacts" in navigator && "ContactsManager" in window;
diff --git a/frontend/discourse/app/services/footer.js b/frontend/discourse/app/services/footer.js
index 4df1c631e5b..34fc9445eaa 100644
--- a/frontend/discourse/app/services/footer.js
+++ b/frontend/discourse/app/services/footer.js
@@ -2,6 +2,7 @@ import { tracked } from "@glimmer/tracking";
import { registerDestructor } from "@ember/destroyable";
import Service from "@ember/service";
import { TrackedSet } from "@ember-compat/tracked-built-ins";
+import EmbedMode from "discourse/lib/embed-mode";
import { disableImplicitInjections } from "discourse/lib/implicit-injections";
@disableImplicitInjections
@@ -10,6 +11,9 @@ export default class FooterService extends Service {
@tracked _showFooterOverride = null;
get showFooter() {
+ if (EmbedMode.enabled) {
+ return false;
+ }
return this._showFooterOverride ?? this.#hiders.size === 0;
}
diff --git a/public/javascripts/embed.js b/public/javascripts/embed.js
index 96ab0ef4af9..a541ce1699c 100644
--- a/public/javascripts/embed.js
+++ b/public/javascripts/embed.js
@@ -38,6 +38,10 @@
queryParams.class_name = DE.className;
}
+ if (DE.fullApp) {
+ queryParams.full_app = "true";
+ }
+
var src = DE.discourseUrl + "embed/comments";
var keys = Object.keys(queryParams);
if (keys.length > 0) {
@@ -57,7 +61,10 @@
iframe.id = "discourse-embed-frame";
iframe.width = "100%";
iframe.frameBorder = "0";
- iframe.scrolling = "no";
+ iframe.scrolling = DE.fullApp ? "yes" : "no";
+ if (DE.fullApp) {
+ iframe.style.height = DE.embedHeight || "600px";
+ }
iframe.referrerPolicy =
DE.discourseReferrerPolicy || "no-referrer-when-downgrade";
comments.appendChild(iframe);
@@ -90,7 +97,7 @@
}
if (e.data) {
- if (e.data.type === "discourse-resize" && e.data.height) {
+ if (e.data.type === "discourse-resize" && e.data.height && !DE.fullApp) {
iframe.height = e.data.height + "px";
}
diff --git a/spec/requests/embed_controller_spec.rb b/spec/requests/embed_controller_spec.rb
index 271f45e21d1..3f230c15012 100644
--- a/spec/requests/embed_controller_spec.rb
+++ b/spec/requests/embed_controller_spec.rb
@@ -186,6 +186,56 @@ RSpec.describe EmbedController do
end
end
+ describe "full_app redirect" do
+ fab!(:embeddable_host)
+
+ before { SiteSetting.embed_full_app = true }
+
+ it "redirects to topic URL with embed_mode when full_app is present" do
+ topic_embed = Fabricate(:topic_embed, embed_url: embed_url)
+
+ get "/embed/comments",
+ params: {
+ embed_url: embed_url,
+ full_app: "true",
+ },
+ headers: {
+ "REFERER" => embed_url,
+ }
+
+ expect(response).to redirect_to("#{topic_embed.topic.url}?embed_mode=true")
+ end
+
+ it "redirects to topic URL with embed_mode when using topic_id" do
+ get "/embed/comments",
+ params: {
+ topic_id: topic.id,
+ full_app: "true",
+ },
+ headers: {
+ "REFERER" => "http://eviltrout.com/some-page",
+ }
+
+ expect(response).to redirect_to("#{topic.url}?embed_mode=true")
+ end
+
+ it "does not redirect when embed_full_app is disabled" do
+ SiteSetting.embed_full_app = false
+ topic_embed = Fabricate(:topic_embed, embed_url: embed_url)
+
+ get "/embed/comments",
+ params: {
+ embed_url: embed_url,
+ full_app: "true",
+ },
+ headers: {
+ "REFERER" => embed_url,
+ }
+
+ expect(response.status).to eq(200)
+ end
+ end
+
context "with a host" do
fab!(:embeddable_host)
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index 9636b512b60..79dbbe58810 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -6669,4 +6669,55 @@ RSpec.describe TopicsController do
}.to change { TopicViewItem.count }
end
end
+
+ describe "allow_embed_mode" do
+ fab!(:topic)
+
+ before { SiteSetting.embed_full_app = true }
+
+ it "keeps X-Frame-Options when embed_mode param is missing" do
+ get("/t/#{topic.slug}/#{topic.id}")
+ expect(response.headers["X-Frame-Options"]).to eq("SAMEORIGIN")
+ end
+
+ it "keeps X-Frame-Options when embed_mode is present but referer is invalid" do
+ get("/t/#{topic.slug}/#{topic.id}", params: { embed_mode: "true" })
+ expect(response.headers["X-Frame-Options"]).to eq("SAMEORIGIN")
+ end
+
+ it "strips X-Frame-Options when embed_mode is present and referer matches embeddable host" do
+ Fabricate(:embeddable_host, host: "example.com")
+ get(
+ "/t/#{topic.slug}/#{topic.id}",
+ params: {
+ embed_mode: "true",
+ },
+ headers: {
+ "HTTP_REFERER" => "https://example.com/page",
+ },
+ )
+ expect(response.headers).not_to include("X-Frame-Options")
+ end
+
+ it "strips X-Frame-Options when embed_mode is present and embed_any_origin is enabled" do
+ SiteSetting.embed_any_origin = true
+ get("/t/#{topic.slug}/#{topic.id}", params: { embed_mode: "true" })
+ expect(response.headers).not_to include("X-Frame-Options")
+ end
+
+ it "keeps X-Frame-Options when embed_full_app is disabled" do
+ SiteSetting.embed_full_app = false
+ Fabricate(:embeddable_host, host: "example.com")
+ get(
+ "/t/#{topic.slug}/#{topic.id}",
+ params: {
+ embed_mode: "true",
+ },
+ headers: {
+ "HTTP_REFERER" => "https://example.com/page",
+ },
+ )
+ expect(response.headers["X-Frame-Options"]).to eq("SAMEORIGIN")
+ end
+ end
end
diff --git a/spec/system/embed_mode_spec.rb b/spec/system/embed_mode_spec.rb
new file mode 100644
index 00000000000..38dcfcf97f6
--- /dev/null
+++ b/spec/system/embed_mode_spec.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+describe "Embed mode", type: :system do
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before { SiteSetting.embed_full_app = true }
+
+ it "applies embed-mode class to body when embed_mode=true" do
+ visit("/t/#{topic.slug}/#{topic.id}?embed_mode=true")
+
+ expect(page).to have_css("body.embed-mode")
+ end
+
+ it "does not apply embed-mode class without the param" do
+ visit("/t/#{topic.slug}/#{topic.id}")
+
+ expect(page).to have_no_css("body.embed-mode")
+ end
+
+ it "hides suggested topics in embed mode" do
+ Fabricate(:post) # create another topic for suggestions
+ visit("/t/#{topic.slug}/#{topic.id}?embed_mode=true")
+
+ expect(page).to have_css("body.embed-mode")
+ expect(page).to have_no_css(".suggested-topics")
+ end
+
+ it "loads topic content without JS errors" do
+ visit("/t/#{topic.slug}/#{topic.id}?embed_mode=true")
+
+ expect(page).to have_css("body.embed-mode")
+ expect(topic_page).to have_topic_title(topic.title)
+ expect(page).to have_css("#post_1")
+ end
+end