Embed Discourse comments on another website via Javascript

Discourse has the ability to embed the comments from a topic in a remote site using a Javascript API that creates an IFRAME. For an example of this in action, check out Coding Horror’s blog. The blog is run via Ghost but the comments are embedded from his Discourse forum.

One important thing to note with this setup is that users have to navigate to your forum to post replies. This is intentional, as we feel that the posting interface on a Discourse forum is currently much richer than what we could embed via Javascript.

This guide will show how to set up comment embedding on your own blog or web site.

How it works

In Discourse, a topic is made up of many posts. When you are embedding Discourse on another site, you are linking a document (blog entry, HTML page, etc.) with a single topic. When people post in that topic, their comments will automatically show up on the page you embedded it in.

You have the choice to have Discourse create the topics automatically when a new embedding is found, or you can create the topics yourself in advance.

Configuring Discourse for Embedding (simple setup)

The following setup will embed a comment feed on a page on a fake blog URL of http://example.com/blog/entry-123.html, from a discourse forum running at =DISCOURSE=.

Domain for  

Domain for  

  1. Visit Admin > Customize > Embedding on your Discourse install. https://=DISCOURSE=/admin/customize/embedding

  2. Create at least one Embeddable Host. This should be the hostname (domain) where you want to embed your comments. In this case the host is =BLOG= – note the lack of http:// and path.

    • Path Allowlist allows you to specify the paths on the remote host that would accept your embed.

    • Post to Category - if you supply a category alongside the host you are entering, posts imported from that host will automatically end up in that category. Different hosts can post to different categories.

    • Tags - you can assign tags to be automatically applied to topics created from a given host.

    • Post Author - you can optionally override the topic creation user on a per-host basis. If not set, the default from the Posts and Topics tab is used.

  3. Navigate to the Posts and Topics tab and fill in the Username for topic creation field. This is the user who will create topics when new embeddings are found. Let’s assume our discourse has a user called eviltrout, so the value is eviltrout.

  4. Insert the following HTML on the web page at http://=BLOG=/blog/entry-123.html

<div id='discourse-comments'></div>

<script type="text/javascript">
  DiscourseEmbed = {
    discourseUrl: 'https://discourse.example.com/',
    discourseEmbedUrl: 'http://example.com/blog/entry-123.html',
    // className: 'CLASS_NAME',
  };

  (function() {
    var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;
    d.src = DiscourseEmbed.discourseUrl + 'javascripts/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);
  })();
</script>

The configurable parts of the snippet are in the DiscourseEmbed object. discourseUrl is the full path to the base of your discourse, including the trailing slash. The discourseEmbedUrl is the document that is currently embedding a comment feed.

If you set this up correctly, the first time you visit http://=BLOG=/blog/entry-123.html it will try to load comments for the blog post. Since there are none, it will tell the Discourse forum to create a new topic in the background. A new topic will be created by eviltrout and the contents of the first post will be crawled from your blog and the text will be extracted automatically.

Once the new topic is created, users can post on it, and their comments will automatically be displayed the next time http://=BLOG=/blog/entry-123.html is visited.

className is optional and will add a class of your choice to the embed so you can customize it with CSS.

:bulb: Tip: If your blog has multiple authors, you can add a <meta name="discourse-username" content="author_username"> tag to each page. When Discourse crawls the page to create the topic, it will use this meta tag to determine the post author, overriding the default username set in the admin settings.

Embedding on more than one page

In the above example we hard coded our http://=BLOG=/blog/entry-123.html URL when embedding the snippet of Javascript. This usually won’t be enough as many sites have many pages that are generated automatically. For example on a blog each entry typically gets its own page. To support this, put the same snippet on each page you want to display comments on, but replace the value passed to discourseEmbedUrl with the current page’s URL. On my blog, I use the following value for discourseEmbedUrl: 'http://eviltrout.com<%= current_page.url %>' – as new blog pages are created, new topics will be created for them automatically on Discourse.

Styling your Embedded content

You have the ability to add a stylesheet for your embedded comments. Use the Embedded CSS section of the Theme editor at Admin > Customize > Themes > [your theme] > Edit CSS/HTML and you can add a custom stylesheet that will be served up with your embedded comments. By default we think the layout looks nice on a white background, but if your site has a unique layout you’ll want to style it yourself.

(Optional) Adding a Feed for Polling

As mentioned above, Discourse will automatically crawl any site it is embedded on. However, sometimes HTML can be hard to parse and it might not extract the contents of your posts correctly. Many blogs and web sites support RSS/Atom feeds for syndication, and Discourse can use this to extract the content of your blog posts more accurately.

Discourse ships with the RSS Polling plugin (included by default). If you have a RSS or Atom feed set up on the site you are embedding Discourse into, you can enable the rss_polling_enabled site setting and add your feed’s URL via Admin > Plugins > RSS Polling. Once the feed URL has been added, Discourse will parse the feed and publish its posts to the appropriate category based on the Allowed Hosts that you add to your Embedding settings.

(Alternate Configuration) Linking to existing topics

Some people prefer to not have Discourse create topics for them automatically on their forums. They’d like to create the topics themselves, then simply tell their embedding code what topic they want to associate with. You can do this by slightly changing your embedding code:

<div id='discourse-comments'></div>

<script type="text/javascript">
  window.DiscourseEmbed = {
    discourseUrl: 'https://=DISCOURSE=/',
    topicId: 12345
  };

  (function() {
    var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;
    d.src = window.DiscourseEmbed.discourseUrl + 'javascripts/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);
  })();
</script>

The only difference here is we’ve replaced discourseEmbedUrl with the id of a topic from Discourse. If you do this, no topic will be created and the comments from that topic will automatically be displayed.

Setting the referrer policy

Due to recent (September 2020) changes to the default referrer policy that is set by many browsers, Discourse now explicitly defaults to setting the iframe’s referrer policy to "no-referrer-when-downgrade". If, for security reasons your site requires a stricter referrer policy, it can be set by adding a discourseReferrerPolicy value to the embed script’s DiscourseEmbed object. For example:

DiscourseEmbed = { discourseUrl: 'https://forum.example.com/',
                                  discourseEmbedUrl: '<your_posts_canonical_URL>',
                                  discourseReferrerPolicy: 'strict-origin-when-cross-origin'};

Programmatically querying the Embed details

We have an API endpoint to query the Embed details using the embed_url as the parameter:

curl 'https://meta.discourse.org/embed/info?embed_url=https://blog.discourse.org/2021/04/discourse-team-grows-to-50' -H 'API-KEY: logapikeygoeshere' -H 'API-USERNAME: apiusernamehere' 

And the response is:

{
  "topic_id": 187794,
  "post_id": 925017,
  "topic_slug": "discourse-team-grows-to-50-blog",
  "comment_count": 2
}

Embedding comments from a private site

For private Discourse instances, if Discourse is on a subdomain of the blog’s domain, comments will be displayed for users who are logged into Discourse. Users who are not logged into Discourse will see a ‘refused to connect’ message. If Discourse and the blog are on completely separate domains, no comments will be displayed for private forums.

Troubleshooting

The most common issue users have when embedding Discourse is setting the correct value for the embeddable hosts you added. Make sure to double check that it is only the domain of your site, and contains no extra slashes or invalid characters.

Last edited by @JammyDodger 2024-05-26T06:44:14Z

Check documentPerform check on document:
116 лайков
Deeply integrating Discourse into website
Is it possible to test Discourse Embed comment on localhost?
Discourse 1.4 Released!
Is it possible to use Discourse as a "commenting system"?
Trouble connecting drupal and discourse
Create topic when a link is clicked
Using Discourse as a comment system
Using Discourse in a web app
Learning Management Systems
Can be integrated with liquid templates?
Discourse blog comments like your blog comments
Embedded Comments iframe Height
Comment Reply Threading / Linking on the WordPress Side
Using Discourse to power comments in an event system or blog?
Cannot get embedding to work
What software you use for blog.discourse.org?
News Plugin :newspaper:
What is Discourse Blog built with?
Embedded topic comments are missing if containing page's URL includes a fragment identifier
Imported topic via embedding will not render normally
Anybody using Discourse for Blog Comments on a Gatsby site?
Integrating Discourse with a larger social network app?
Using Discourse as commenting system via JavaScript: Delay load or load on scroll
Use Discourse as the comments section of a Jekyll site?
"Error Embedding" comments
Shared Discourse/Static Site Login
Discourse + Ghost Blog Integration. Is my Understanding Wrong?
Trying to do embedding. Hit with “The referer did not match any of the following hosts:” issue
Looking for Ruby-based CMS recommendations as a compliment to Discourse
[Paid] Embedding: Allowing one RSS feed and one username per host
Discourse comment-like discussion
Discourse embedding error: Failed to execute postMessage on DOMWindow
Discourse + Ghost integration and SEO
Error Embedding
Hide or remove "Listed/Unlisted" comments when embedded
Display all posts in embedding topics with +100 comments
Embedding Topic topic-map or Topic Summary on Other Site
Wordpress integration by iFrame instead of sync
Not generate topic automatically for all blog posts
Link to Discourse topic without displaying Comments (in Drupal)
Which CMS for Discourse
Understanding how embedding works on remote site
Arguments against integrated intranet solutions?
Embed single discourse Topics to articles on news website
Displaying comments embed as a link without using the WP plugin
Get right title embedding comments
Disqus-like commenting on Wordpress
Embedding Discourse Comments *without* Javascript
How to integrate in discourse in zenodo
Co-author topics
How might we better structure #howto?
Issue with image uploads on embedded topics
Getting Discourse URL on embedded comments
Integrating registered users notifications+avatar into static website
Pandoc integration
Can I use Discourse to add Commenting to my Blogs?
How can I get the list of Discourse Topic IDs dynamically
[Question/Request] Featured image url for post
JS embed fails with "Job exception: invalid stored block lengths (Zlib::DataError)"
No `Referer:`, no embedding
Commenting system: integrate Discourse and Webflow
WP Discourse Embed Plugin
Embedding error
Best option to have category "hidden" on Discourse, but otherwise accessible if you have the link?
Topic list on the right side
Create an empty topic via API
Using Discourse for Comments?
Add button with link post forum
Add button with link post forum
Discourse embed crawls cookie warning text
The Gamification of Discourse
Embedding Discourse comment box to blog page
Pinned topic summary is using first-line link text instead of body text
Nextcloud support
Discourse comment button on blog?
Is there a Disqus like comment implementation?
One Discourse instance, Two Blogs?
Embeddable Discourse activity widget
Blog Post Styling
Integration: Discourse comments in Gitbook
Is it possible to autologin discourse via iframe?
Widget to embed in 3rd party websites
How to customize the text in an embedded post?
Benefits to using WP comments over JS embed?
Benefits to using WP comments over JS embed?
What CSS was used for Comments here?
Setting canonical URL when posting/cross-posting
Embed comments from Discourse in your single page app
Embedded site stuck at "Loading Discussions"
Embedding Categories in Existing SPA
[Update] Simplify embed feature
Does setting the discourseUrl prevent other clients from creating embedded posts for moved pages?
To use Discourse completely on shopify
I'm unsure of how oneboxing is setup for blog posts to Discourse
I'm unsure of how oneboxing is setup for blog posts to Discourse
Embed my Discourse Forum as IFrame
Discourse blog (article and comments)
Most efficient way to use Discourse for comments on Shopify blog posts?
Is the Discourse content markdown toolbar available as a standalone?
Is there a blog plugin for Discourse's meta blog implementations?
Discourse Comments stuck on "Loading..."
Topic Ratings Plugin
Discourse implementation in create react app
Embed forum
BricksForge and Bricks API Query Builder with Discourse
Wordpress posts are now unlisted from latest update of forum and plugin
Most efficient way to use Discourse for comments on Shopify blog posts?
AI sockpuppet accounts to jumpstart my community?
Should Discourse make an effort to become a viable comment platform?
Problem embeding a topic in a page on another domain
Want to set internal forum on our reactjs member's platform
Embed Discourse using external_id
Expose external_id in embed.js
Grow my community
Forbidden error on embed widget
Strapi discourse integration
Migrating embedded topics from topicId to automatic topic creation
Migrating embedded topics from topicId to automatic topic creation
Problem with "Publish as Unlisted Topics"
RSS Polling
Failed to execute 'postMessage' on 'DOMWindow'
Failed to execute 'postMessage' on 'DOMWindow'
RSS plugin default show full post
Is there a Disqus like comment implementation?
Embending topic in 'another' website. And change redirect page after login
Embedding full threads - possible?
How to customize the text in an embedded post?
How to show the latest discussion on the front page of our main website
Embed Most Recent Replies To Post in Specific Category
Is anyone using Discourse in higher ed for courses?
Embed a list of Discourse topics onto an external site
Is Discourse a full website or just a forum add-in?
Is Discourse a full website or just a forum add-in?
Can I send an external URL to the Discourse API for it to return topics linking to that URL?
How to use Discourse API for article forums and independent community spaces
Threaded comments when using Discourse for website comments?
Bug with URLs in Embedded Comments
Blog posts would be nicer if authored by an identifiable person
Embed Discourse as a full comment system on your site
Embedded comments dates are still not localized
Embed Discourse as a full comment system on your site
Structuring an active support community migrating from Facebook
Embed Discourse as a full comment system on your site
Where in Discourse can users publicly share PII?
"Show Full Post" button doesn't work in subfolder installations
"Show Full Post" button doesn't work in subfolder installations
How to Enable Terms of Service and Privacy Policy Pages in Discourse?
JavaScript embed won’t display embed, console log shows: Failed to execute postMessage on DOMWindow…
Can i use / embed discourse to make comments on pages hosted for example on Aquia
Emoji are huge when embedding
Set topic title with Discourse Embed
Embedding Discourse Profile via Javascript
WP-discourse: comments are not pulled over
discourseEmbed, does not match recipient window origin
Statamic integration
How to embed whole forum in another site
Possible to add comment count (to a Ghost blog)?
How can I delete or undelete topics?
Link existing forum topic to new WordPress post
How to enable Discourse comments via JavaScript in Wordpress?
How to link the existing discourse comments to wordpress posts?
Embed whole forum
WP Discourse Embed Plugin
WP Discourse Embed Plugin
Synchronising log out of discourse when logging out of WordPress
Topic as widget
Discourse a a comment system with React Native and Meteor
A post's TopicEmbed isn't destroyed when the post is deleted
Pages from Google search are not rendering
Controlling amount of embedded text
Zendesk Article Comment in Discourse Integration
Flood of new topics from Embedded Discourse
Discourse topics as Dokuwiki talk pages
Multiple cors origins on hosted discourse?
WordPress / Discourse API Strategy: Get Reply Count via API Efficiently
Error Embedding for existing posts
Making embedded JavaScript based discourse commenting responsive
[paid] Preference to create & embed a topic via JavaScript only when a user clicks the "Start Discussion" link
Embedding: Discussion not showing up for new posts
Allowing WP comments while showing Discourse comments too
Handling large pictures of embedded comments inside jquery window
"Error Embedding" comments
Embedded comments not displayed due to X-Frame-Options DENY
Failed to execute postMessage on DOMWindow: The target origin provided does not match
Embedding Discourse сomments with GitBook

Is it possible to use this method if the Discourse category is hidden from public view?

Probably not, but it might work if all of your viewers are logged in.

Я создал обучающее руководство, которое проведет вас через процесс настройки локального экземпляра Discourse на Vagrant для ваших локальных тестов, чтобы внедрить Discourse в проект фронтенд-разработки. Вы можете найти его здесь: Local discourse: vagrant, ansible, lxd, docker, discourse-embedding

Это отличается от других описаний, которые я находил ранее, тем, что позволяет запустить локально полную настройку Discourse, как это делается в продакшене, чтобы получить представление о «реальном» процессе настройки. Кроме того, эта настройка может служить локальной игровой площадкой для разработки при внедрении Discourse в ваш проект.

2 лайка

Привет, есть ли способ отключить встраивание для черновиков? В Ghost я не вижу обработчика для статуса поста. Можно ли изменить настройки встраивания, чтобы исключить /p/, который используется для предпросмотра постов? У меня проблема: посты, которые просматриваются, добавляются в Discourse. Спасибо.

Не могу найти настройку для стилизации iframe с embed-контентом… Может, оригинальный пост устарел?

РЕДАКТИРОВАНИЕ: Всё в порядке, она просто переместилась. Я могу добавить её в компонент темы :slight_smile: спасибо!

2 лайка

Звучит как вопрос по Ghost, а не по Discourse? Однако ваша интеграция с Ghost должна это учитывать, а не Discourse.

3 лайка

Всем привет! Мне нужна помощь с внедрением Discourse в READTHEDOCS (используя Sphinx). У кого-то есть такой опыт?

1 лайк

Похоже, существует GitHub - pdavide/sphinxcontrib-discourse · GitHub, который всегда встраивает одну тему.

6 лайков

Спасибо за ответ, давайте проверим.

Привет, ребята!
У меня возникли проблемы с встраиванием в конкретную тему:
Я пробовал разные варианты настроек, но на моём сайте всё равно появляется «Ошибка встраивания».
Можно ли заметить, что я делаю не так? Я потратил целую вечность, пытаясь заставить это работать, любая помощь будет очень кстати.

Текущий код, встроенный на сайт

Есть ли ошибки в консоли JavaScript?

На вашем первом скриншоте все пути настроены на публикацию в категорию «Без категории». Если вы хотите публиковать все сообщения в одну и ту же категорию, достаточно создать только одну запись хоста Embeddable.

Значения «Белый список путей» (Path Whitelist), которые вы добавили в записи хоста, могут вызывать проблемы. Вы можете оставить это поле пустым, чтобы публиковать все сообщения с вашего блога, на который добавлен скрипт встраивания Discourse. Если вы хотите настроить публикацию сообщений из конкретного пути в категорию Discourse, путь должен заканчиваться на /.*. Например, /sites/.*.

Двойная косая черта в начале пути /t/newsletter-discussions/105 может быть причиной проблемы. Кроме того, это похоже на путь к теме в Discourse. Если вы его указываете, путь должен вести к группе сообщений на вашем блоге. Назначение настройки «Белый список путей» — позволять публиковать сообщения из конкретного пути на вашем блоге в конкретную категорию Discourse.

5 лайков

Хорошо, спасибо, Саймон, я ценю это. Я попробую.

Как и @codinghorror, я также использую эту интеграцию Discourse с Ghost с использованием стандартной конфигурации, где в качестве discourseEmbedURL используется абсолютный URL.

Около недели назад я решил изменить маршрутизацию моего блога Ghost так, чтобы посты с URL-адресами вроде https://engineerworkshop.com/2020/02/20/how-to-set-up-wireguard-on-a-raspberry-pi/ перенаправлялись на https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/, причем https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/ стал новым постоянным URL (permalink).

Проблема

Вы, вероятно, можете предугадать проблему, которую это создаёт: параметр discourseEmbedURL установлен на старый URL, поэтому при вызове скрипта встраивания, который теперь имеет другой URL, в Discourse создаётся новая тема комментариев.

Попытка решения (которая не удалась)

До этого я предвидел эту проблему и подумал, что проявил хитрость, используя шаблон регулярного выражения с командой remap для исправления URL: rake posts:remap["[0-9]{4}\/[0-9]{2}\/[0-9]{2}","blog",regex]

Хотя это и «отчасти» сработало, к сожалению, везде, где URL использовался в оригинальном комментарии Discourse, при загрузке постов блога в Discourse создавались новые темы комментариев.

В итоге я просто перезагрузил каждый пост на своём сайте и перенёс комментарии из старых тем в новые, удалив оригиналы (знаю, знаю). Очевидно, что удаление страниц плохо сказывается на SEO, не говоря уже об опыте конечного пользователя.

Мой вопрос

Я предполагаю, что причина неудачи моей попытки исправления через регулярное выражение заключается в том, что тема Discourse каким-то образом привязана к URL на стороне сервера. (Я с готовностью признаю, что не знаком со структурой данных Discourse). Для будущих знаний и для всех, кто может попытаться сделать то же самое в будущем, существует ли способ переназначить тему Discourse на новый URL поста блога?

Заранее спасибо!

5 лайков

7 сообщений были объединены в существующую тему: WP Discourse Embed Plugin

Мне очень нравится эта функция, так как у меня много сайтов с контентом в стиле журналов, и я могу автоматически генерировать темы для наших форумов. Но есть ли способ заставить предварительный просмотр URL работать так же, как обычно в Discourse?

То есть вместо этого:

Больше похоже на это:

Спасибо,
Джим

3 лайка

Если у вас есть ссылка на отдельной строке, она должна отображаться в виде Onebox.
Затем разместите ниже всю строку с описанием, включая ссылку, как показано на вашем первом изображении. Это появится под ссылкой в формате Onebox.

2 лайка

Хм… это немного проблематично, поскольку сама страница и является тем, что предпросматривается. Поэтому размещение ссылки в самом верху HTML-кода страницы или текста статьи создаёт определённые трудности. Вот ссылка на обсуждаемую страницу:

https://modelshipwrights.com/news/us-navy-light-cruiser-cl-89-miami

3 лайка

Всем привет. Я почти добился успеха, но понял, что сценарий, который я задумал, может оказаться не таким простым, как я надеялся, и я не уверен, сколько дополнительной работы это потребует.

Я надеюсь использовать эту функцию для организации обсуждений на сайте, основанном на пользовательском контенте. У меня нет проблем с встраиванием комментариев или настройкой единого входа (SSO), чтобы мои пользователи автоматически становились участниками моего сообщества с теми же адресами электронной почты, именами пользователей и т. д.

Я надеялся, что при создании нового пользовательского контента на моём сайте пользователь, который его опубликовал, станет автором связанного поста в Discourse, а не один единственный пользователь, определённый в настройке «Имя пользователя для создания темы» функции встраивания. Я не буду разрешать регистрацию вне моего текущего процесса регистрации, поэтому я на 100% уверен, что пользователь Discourse уже существует или, по крайней мере, может быть создан в момент создания новой темы.

Надеюсь, очевидно, зачем мне это нужно. То есть создатель контента станет автором обсуждения (OP) на моём сайте Discourse, будет автоматически подписан на тему и получать уведомления о ответах, его посты будут выделены, чтобы отличаться от других комментариев и так далее.

Есть ли какие-либо предложения, с чего начать?

Спасибо!

3 лайка