Intégrer les commentaires Discourse sur un autre site web via Javascript

Discourse a la capacité d’intégrer les commentaires d’un sujet sur un site distant à l’aide d’une API Javascript qui crée une IFRAME. Pour un exemple de cela en action, consultez le blog de Coding Horror. Le blog est géré via Ghost mais les commentaires sont intégrés depuis son forum Discourse.

Une chose importante à noter avec cette configuration est que les utilisateurs doivent naviguer vers votre forum pour publier des réponses. Ceci est intentionnel, car nous estimons que l’interface de publication sur un forum Discourse est actuellement beaucoup plus riche que ce que nous pourrions intégrer via Javascript.

Ce guide vous montrera comment configurer l’intégration de commentaires sur votre propre blog ou site web.

Comment ça marche

Dans Discourse, un sujet est composé de nombreux messages. Lorsque vous intégrez Discourse sur un autre site, vous liez un document (article de blog, page HTML, etc.) à un seul sujet. Lorsque les gens publient dans ce sujet, leurs commentaires apparaîtront automatiquement sur la page sur laquelle vous l’avez intégré.

Vous avez le choix de laisser Discourse créer les sujets automatiquement lorsqu’une nouvelle intégration est détectée, ou vous pouvez créer les sujets vous-même à l’avance.

Configuration de Discourse pour l’intégration (configuration simple)

La configuration suivante intégrera un flux de commentaires sur une page d’une fausse URL de blog de http://example.com/blog/entry-123.html, à partir d’un forum discourse fonctionnant à =DISCOURSE=.

Domaine de 

Domaine pour 

  1. Visitez Admin > Personnaliser > Intégration sur votre installation Discourse. https://=DISCOURSE=/admin/customize/embedding

  2. Créez au moins un Hôte intégrable. Il doit s’agir du nom d’hôte (domaine) où vous souhaitez intégrer vos commentaires. Dans ce cas, l’hôte est =BLOG= – notez l’absence de http:// et de chemin.

    • Liste d’autorisation des chemins vous permet de spécifier les chemins sur l’hôte distant qui accepteront votre intégration.

    • Publier dans la catégorie - si vous fournissez une catégorie avec l’hôte que vous entrez, les messages importés de cet hôte se retrouveront automatiquement dans cette catégorie. Différents hôtes peuvent publier dans différentes catégories.

    • Balises - vous pouvez attribuer des balises à appliquer automatiquement aux sujets créés à partir d’un hôte donné.

    • Auteur du message - vous pouvez facultativement remplacer l’utilisateur créant le sujet par hôte. Si non défini, la valeur par défaut de l’onglet Messages et Sujets est utilisée.

  3. Accédez à l’onglet Messages et Sujets et remplissez le champ Nom d’utilisateur pour la création de sujet. C’est l’utilisateur qui créera les sujets lorsque de nouvelles intégrations seront trouvées. Supposons que notre discours ait un utilisateur nommé eviltrout, la valeur est donc eviltrout.

  4. Insérez le HTML suivant sur la page web à l’adresse 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>

Les parties configurables du fragment se trouvent dans l’objet DiscourseEmbed. discourseUrl est le chemin complet vers la base de votre discourse, y compris la barre oblique finale. discourseEmbedUrl est le document qui intègre actuellement un flux de commentaires.

Si vous configurez cela correctement, la première fois que vous visitez http://=BLOG=/blog/entry-123.html, il tentera de charger les commentaires pour l’article de blog. Comme il n’y en a pas, il demandera au forum Discourse de créer un nouveau sujet en arrière-plan. Un nouveau sujet sera créé par eviltrout et le contenu du premier message sera exploré depuis votre blog et le texte sera extrait automatiquement.

Une fois que le nouveau sujet est créé, les utilisateurs peuvent y publier, et leurs commentaires seront automatiquement affichés la prochaine fois que http://=BLOG=/blog/entry-123.html sera visité.

className est facultatif et ajoutera une classe de votre choix à l’intégration afin que vous puissiez la personnaliser avec du CSS.

:bulb: Astuce : Si votre blog a plusieurs auteurs, vous pouvez ajouter une balise <meta name="discourse-username" content="author_username"> à chaque page. Lorsque Discourse explorera la page pour créer le sujet, il utilisera cette balise meta pour déterminer l’auteur du message, annulant le nom d’utilisateur par défaut défini dans les paramètres d’administration.

Intégration sur plus d’une page

Dans l’exemple ci-dessus, nous avons codé en dur notre URL http://=BLOG=/blog/entry-123.html lors de l’intégration du fragment de Javascript. Cela ne suffira généralement pas car de nombreux sites comportent de nombreuses pages générées automatiquement. Par exemple, sur un blog, chaque entrée reçoit généralement sa propre page. Pour prendre en charge cela, placez le même fragment sur chaque page sur laquelle vous souhaitez afficher des commentaires, mais remplacez la valeur passée à discourseEmbedUrl par l’URL de la page actuelle. Sur mon blog, j’utilise la valeur suivante pour discourseEmbedUrl : 'http://eviltrout.com<%= current_page.url %>' – à mesure que de nouvelles pages de blog sont créées, de nouveaux sujets seront créés pour elles automatiquement sur Discourse.

Stylisation de votre contenu intégré

Vous avez la possibilité d’ajouter une feuille de style pour vos commentaires intégrés. Utilisez la section CSS intégré de l’éditeur de thème à Admin > Personnaliser > Thèmes > [votre thème] > Modifier CSS/HTML et vous pourrez ajouter une feuille de style personnalisée qui sera servie avec vos commentaires intégrés. Par défaut, nous pensons que la mise en page est agréable sur un fond blanc, mais si votre site a une disposition unique, vous voudrez la styliser vous-même.

(Facultatif) Ajout d’un flux pour le sondage

Comme mentionné ci-dessus, Discourse explorera automatiquement tout site sur lequel il est intégré. Cependant, le HTML peut parfois être difficile à analyser et il se peut qu’il n’extraie pas correctement le contenu de vos messages. De nombreux blogs et sites web prennent en charge les flux RSS/Atom pour la syndication, et Discourse peut l’utiliser pour extraire le contenu de vos articles de blog plus précisément.

Discourse est livré avec le plugin de sondage RSS (inclus par défaut). Si vous avez un flux RSS ou Atom configuré sur le site dans lequel vous intégrez Discourse, vous pouvez activer le paramètre de site rss_polling_enabled et ajouter l’URL de votre flux via Admin > Plugins > Sondage RSS. Une fois l’URL du flux ajoutée, Discourse analysera le flux et publiera ses messages dans la catégorie appropriée en fonction des Hôtes Autorisés que vous ajoutez à vos paramètres d’Intégration.

(Configuration alternative) Lien vers des sujets existants

Certaines personnes préfèrent ne pas laisser Discourse créer automatiquement des sujets sur leurs forums. Elles souhaitent créer les sujets elles-mêmes, puis simplement indiquer au code d’intégration quel sujet associer. Vous pouvez le faire en modifiant légèrement votre code d’intégration :

<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>

La seule différence est que nous avons remplacé discourseEmbedUrl par l’identifiant d’un sujet de Discourse. Si vous faites cela, aucun sujet ne sera créé et les commentaires de ce sujet seront affichés automatiquement.

Définition de la politique de référent

En raison des modifications récentes (septembre 2020) apportées à la politique de référent par défaut définie par de nombreux navigateurs, Discourse définit désormais explicitement par défaut la politique de référent de l’iframe sur \"no-referrer-when-downgrade\". Si, pour des raisons de sécurité, votre site nécessite une politique de référent plus stricte, celle-ci peut être définie en ajoutant une valeur discourseReferrerPolicy à l’objet DiscourseEmbed du script d’intégration. Par exemple :

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

Interrogation programmatique des détails de l’intégration

Nous disposons d’un point de terminaison d’API pour interroger les détails de l’intégration en utilisant l’embed_url comme paramètre :

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' 

Et la réponse est :

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

Intégration des commentaires à partir d’un site privé

Pour les instances privées de Discourse, si Discourse se trouve sur un sous-domaine du domaine du blog, les commentaires seront affichés pour les utilisateurs connectés à Discourse. Les utilisateurs qui ne sont pas connectés à Discourse verront un message de « connexion refusée ». Si Discourse et le blog se trouvent sur des domaines complètement séparés, aucun commentaire ne sera affiché pour les forums privés.

Dépannage

Le problème le plus courant rencontré par les utilisateurs lors de l’intégration de Discourse est la définition de la valeur correcte pour les hôtes intégrables que vous avez ajoutés. Assurez-vous de vérifier qu’il s’agit uniquement du domaine de votre site, et qu’il ne contient pas de barres obliques supplémentaires ou de caractères non valides.

116 « J'aime »
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
Learning Management Systems
Using Discourse in a web app
Using Discourse as a comment system
Comment Reply Threading / Linking on the WordPress Side
Discourse blog comments like your blog comments
Can be integrated with liquid templates?
Embedded Comments iframe Height
Use Discourse as the comments section of a Jekyll site?
Using Discourse to power comments in an event system or blog?
Using Discourse as commenting system via JavaScript: Delay load or load on scroll
Cannot get embedding to work
News Plugin :newspaper:
Embedded topic comments are missing if containing page's URL includes a fragment identifier
Imported topic via embedding will not render normally
Integrating Discourse with a larger social network app?
What is Discourse Blog built with?
Anybody using Discourse for Blog Comments on a Gatsby site?
What software you use for blog.discourse.org?
"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
Threaded comments when using Discourse for website comments?
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
How to Enable Terms of Service and Privacy Policy Pages in Discourse?
Bug with URLs in Embedded Comments
Blog posts would be nicer if authored by an identifiable person
Structuring an active support community migrating from Facebook
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
Embed comments from Discourse in your single page app
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.

I’ve created a tutorial that walks you through the process of setting up a local discourse instance on vagrant for your local tests to embed discourse in your front-end development project. You can find it here: Local discourse: vagrant, ansible, lxd, docker, discourse-embedding

This is different from other descriptions that I found before in that it allows you to run locally a complete discourse set-up like you would do in production to get a feel for the “real” set-up process. In addition this set-up is able to serve as a local development playground for embedding discourse into your project.

2 « J'aime »

Hi, is there a way to disable embedding for posts in draft status? I can’t see any handlebar within Ghost for post status, can I change the embed settings to exclude /p/ which is used to preview posts? I have a problem where posts that are previewed are being added to Discourse. Cheers.

Can’t seem to find the setting to style the embedding iframe any more…? Is the original post out of date somehow?

EDIT: Nevermind, it had just changed places. I can add it to a theme component :slight_smile: thanks!

2 « J'aime »

This sounds like a ghost question, not a Discourse question? However your Ghost integration is working needs to take that into account, not Discourse.

3 « J'aime »

Hello everyone!
I need some help to embed Discourse into READTHEDOCS (using Sphinx)
Does anyone have this kind of experience?

1 « J'aime »

Looks like there is GitHub - pdavide/sphinxcontrib-discourse which always embed a single topic.

6 « J'aime »

Thank you for reply, let check it out

Hey Guys
I’ve been having some trouble embedding to a specific topic:
I’ve been trying different variations of settings and I still just get ‘Error Embedding’ On My Website.
Is it noticeable at all what I may be doing wrong? I’ve spent forever trying to get it to work, any help is appreciated.

Current Code Embedded On Website

Are there any errors in your Javascript console?

In your first screenshot, you have all the paths set to publish to the uncategorized category. If you want to publish all posts to the same category you only need to create one Embeddable host record.

The Path Whitelist values that you have added to your Host entries might be causing problems. You can leave that value blank to publish all posts from your blog site that you’ve added the Discourse embed script to. If you want to set a specific path to publish to a Discourse category, the path should end with /.*. For example /sites/.*

The double slash at the start of your /t/newsletter-discussions/105 path may be a problem. Also, that looks like the path to a Discourse topic. If set, the path should be the path to a grouping of posts on your blog. The purpose of the Path Whitelist setting is to allow you to publish posts from a specific path on your blog to a specific Discourse category.

5 « J'aime »

Ok thank you Simon, I appreciate it. I will give this a shot.

Like @codinghorror, I also use this DIscourse integration with Ghost using the stock configuration which uses the absolute URL as the discourseEmbedURL.

A week or so ago, I decided to change my Ghost blog’s routing so that posts with URLs like https://engineerworkshop.com/2020/02/20/how-to-set-up-wireguard-on-a-raspberry-pi/ are redirected to https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/, with https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/ being the new permalink.

The Problem

You can probably anticipate the problem this creates: the discourseEmbedURL is set to the old URL and so when the embed script is called, which now has a different URL, a new comment post is created in Discourse.

Solution Attempt (Which Failed)

Now, prior to this, I had anticipated this problem, and so I thought I was being clever using a regex pattern with remap to fix the URLs: rake posts:remap["[0-9]{4}\/[0-9]{2}\/[0-9]{2}","blog",regex]

While that did “sort of” work, wherever the URL was used in the original Discourse comment post, sadly, when I loaded the blog posts, new comment topics were created in Discourse.

Ultimately, I just reloaded every post on my site and transferred comments from the old topics to my new topics, deleting the originals (I know, I know). Obviously killing pages is bad for SEO, not to mention end-user experience.

My Question

I assume the reason my regex patch attempt didn’t work is because the Discourse topic is somehow keyed to the URL on the backend. (I readily admit to being ignorant of Discourse’s data structure). For future knowledge, and anyone else that may attempt to do the same in the future, is there a way to remap a DIscourse topic to a new blog post URL?

Thanks in advance!

5 « J'aime »

7 posts were merged into an existing topic: WP Discourse Embed Plugin

I love this feature as I have many magazine-style content sites and I can auto generate the topics into our forums but is there a way to get the URL preview working like it does normally in Discourse?

So instead of this:

More like this:

Thanks,
Jim

3 « J'aime »

If you have the link on a separate line by itself it should Onebox.
Then have your entire description line below, including the link, as you show in your first image. That will appear below the Oneboxed link.

2 « J'aime »

Hmm… well that’s a bit of a problem as the page itself is what is being previewed. So putting a link at the very top of the page HTML or article text is kinda problematic. Here is the page in question:

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

3 « J'aime »

Hi folks. I’ve almost got this working, but realised that the use case I had in mind looks like it may not be as straightforward as I had hoped, and I am not sure how much additional work is involved.

I’m hoping to use this feature to power discussions on a site that is based around user generated content. I have no issues with the embedding of comments, or getting SSO set up and ensuring my users automatically become members of my community with the same emails, usernames, etc.

What I was hoping is that, when a new piece of user content is created on my site, that the user who published it becomes the author of the related Discourse post, not a single user as defined in the “Username for topic creation” setting of the embed feature. I won’t be allowing signups outside of my current signup process so I can be 100% sure that the Discourse user will already exist or, at least, can be created at that time we create the new thread.

Hopefully it’s obvious why I’d want to do this. ie. the content creator would then be the discussion’s OP on my Discourse site and could be automatically subscribed to the thread and notified of replies, their posts highlighted so as to stand out from other comments, etc, etc.

Any suggestions on where to start?

Thanks!

3 « J'aime »