Incorporar comentários do Discourse em outro site via Javascript

O Discourse tem a capacidade de incorporar os comentários de um tópico em um site remoto usando uma API Javascript que cria um IFRAME. Para um exemplo disso em ação, confira o blog Coding Horror. O blog é executado via Ghost, mas os comentários são incorporados do seu fórum Discourse.

Uma coisa importante a notar com essa configuração é que os usuários precisam navegar até o seu fórum para postar respostas. Isso é intencional, pois acreditamos que a interface de postagem em um fórum Discourse é atualmente muito mais rica do que o que poderíamos incorporar via Javascript.

Este guia mostrará como configurar a incorporação de comentários no seu próprio blog ou site.

Como funciona

No Discourse, um tópico é composto por várias postagens. Quando você está incorporando o Discourse em outro site, você está vinculando um documento (entrada de blog, página HTML, etc.) a um único tópico. Quando as pessoas postam naquele tópico, seus comentários aparecerão automaticamente na página em que você o incorporou.

Você tem a opção de fazer com que o Discourse crie os tópicos automaticamente quando uma nova incorporação é encontrada, ou pode criar os tópicos você mesmo com antecedência.

Configurando o Discourse para Incorporação (configuração simples)

A configuração a seguir incorporará um feed de comentários em uma página com a URL de um blog falso de http://example.com/blog/entry-123.html, a partir de um fórum discourse executado em =DISCOURSE=.

Domínio para  

Domínio para  

  1. Visite Admin > Personalizar > Incorporação na sua instalação do Discourse. https://=DISCOURSE=/admin/customize/embedding

  2. Crie pelo menos um Host Incorporável (Embeddable Host). Este deve ser o nome do host (domínio) onde você deseja incorporar seus comentários. Neste caso, o host é =BLOG= – note a ausência de http:// e caminho.

    • Lista de Permissão de Caminhos (Path Allowlist) permite que você especifique os caminhos no host remoto que aceitarão sua incorporação.

    • Postar na Categoria (Post to Category) - se você fornecer uma categoria junto com o host que está inserindo, as postagens importadas daquele host acabarão automaticamente naquela categoria. Diferentes hosts podem postar em diferentes categorias.

    • Tags - você pode atribuir tags para serem aplicadas automaticamente aos tópicos criados a partir de um determinado host.

    • Autor da Postagem (Post Author) - você pode opcionalmente substituir o usuário de criação do tópico com base no host. Se não for definido, o padrão da guia Postagens e Tópicos (Posts and Topics) será usado.

  3. Navegue até a guia Postagens e Tópicos (Posts and Topics) e preencha o campo Nome de Usuário para criação de tópico (Username for topic creation). Este é o usuário que criará tópicos quando novas incorporações forem encontradas. Vamos supor que nosso discourse tenha um usuário chamado eviltrout, então o valor é eviltrout.

  4. Insira o seguinte HTML na página da web em 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>

As partes configuráveis do snippet estão no objeto DiscourseEmbed. discourseUrl é o caminho completo para a base do seu discourse, incluindo a barra final. O discourseEmbedUrl é o documento que está atualmente incorporando um feed de comentários.

Se você configurar isso corretamente, na primeira vez que visitar http://=BLOG=/blog/entry-123.html ele tentará carregar os comentários para a postagem do blog. Como não há nenhum, ele informará ao fórum Discourse para criar um novo tópico em segundo plano. Um novo tópico será criado por eviltrout e o conteúdo da primeira postagem será rastreado do seu blog e o texto será extraído automaticamente.

Assim que o novo tópico for criado, os usuários poderão postar nele, e seus comentários serão exibidos automaticamente na próxima vez que http://=BLOG=/blog/entry-123.html for visitado.

className é opcional e adicionará uma classe de sua escolha à incorporação para que você possa personalizá-la com CSS.

:bulb: Dica: Se o seu blog tiver vários autores, você pode adicionar uma tag <meta name="discourse-username" content="author_username"> a cada página. Quando o Discourse rastrear a página para criar o tópico, ele usará esta meta tag para determinar o autor da postagem, substituindo o nome de usuário padrão definido nas configurações de administração.

Incorporando em mais de uma página

No exemplo acima, codificamos nossa URL http://=BLOG=/blog/entry-123.html ao incorporar o trecho de Javascript. Isso geralmente não será suficiente, pois muitos sites têm muitas páginas geradas automaticamente. Por exemplo, em um blog, cada entrada geralmente recebe sua própria página. Para suportar isso, coloque o mesmo snippet em cada página em que deseja exibir comentários, mas substitua o valor passado para discourseEmbedUrl pela URL da página atual. No meu blog, eu uso o seguinte valor para discourseEmbedUrl: 'http://eviltrout.com<%= current_page.url %>' – à medida que novas páginas de blog são criadas, novos tópicos serão criados para elas automaticamente no Discourse.

Estilizando seu conteúdo incorporado

Você tem a capacidade de adicionar uma folha de estilos para seus comentários incorporados. Use a seção CSS Incorporado (Embedded CSS) do editor de Tema em Admin > Personalizar > Temas > [seu tema] > Editar CSS/HTML e você pode adicionar uma folha de estilos personalizada que será servida com seus comentários incorporados. Por padrão, achamos que o layout fica bom em um fundo branco, mas se o seu site tiver um layout exclusivo, você vai querer estilizá-lo você mesmo.

(Opcional) Adicionando um Feed para Sondagem (Polling)

Conforme mencionado acima, o Discourse rastreará automaticamente qualquer site em que esteja incorporado. No entanto, às vezes o HTML pode ser difícil de analisar e pode não extrair o conteúdo de suas postagens corretamente. Muitos blogs e sites suportam feeds RSS/Atom para sindicação, e o Discourse pode usar isso para extrair o conteúdo de suas postagens de blog com mais precisão.

O Discourse vem com o plugin de Sondagem RSS (RSS Polling plugin) (incluído por padrão). Se você tiver um feed RSS ou Atom configurado no site em que está incorporando o Discourse, poderá ativar a configuração do site rss_polling_enabled e adicionar a URL do seu feed via Admin > Plugins > Sondagem RSS (RSS Polling). Assim que o URL do feed for adicionado, o Discourse analisará o feed e publicará suas postagens na categoria apropriada com base nos Hosts Permitidos que você adiciona às suas configurações de Incorporação.

(Configuração Alternativa) Vinculando a tópicos existentes

Algumas pessoas preferem não fazer com que o Discourse crie tópicos para elas automaticamente em seus fóruns. Elas gostariam de criar os tópicos elas mesmas e, em seguida, simplesmente informar ao código de incorporação qual tópico desejam associar. Você pode fazer isso alterando ligeiramente seu código de incorporação:

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

A única diferença aqui é que substituímos discourseEmbedUrl pelo ID de um tópico do Discourse. Se você fizer isso, nenhum tópico será criado e os comentários daquele tópico serão exibidos automaticamente.

Definindo a política de remetente (referrer policy)

Devido a mudanças recentes (setembro de 2020) na política de remetente padrão definida pela maioria dos navegadores, o Discourse agora define explicitamente a política de remetente do iframe como "no-referrer-when-downgrade". Se, por razões de segurança, seu site exigir uma política de remetente mais rigorosa, ela pode ser definida adicionando um valor discourseReferrerPolicy ao objeto DiscourseEmbed do script de incorporação. Por exemplo:

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

Consultando programaticamente os detalhes da Incorporação

Temos um endpoint de API para consultar os detalhes da Incorporação usando o embed_url como parâmetro:

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' 

E a resposta é:

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

Incorporando comentários de um site privado

Para instâncias privadas do Discourse, se o Discourse estiver em um subdomínio do domínio do blog, os comentários serão exibidos para usuários que estão logados no Discourse. Usuários que não estão logados no Discourse verão uma mensagem de ‘recusado a conectar’. Se o Discourse e o blog estiverem em domínios completamente separados, nenhum comentário será exibido para fóruns privados.

Solução de problemas

O problema mais comum que os usuários encontram ao incorporar o Discourse é definir o valor correto para os hosts incorporáveis que você adicionou. Certifique-se de verificar novamente se é apenas o domínio do seu site e se não contém barras extras ou caracteres inválidos.

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

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 curtidas

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 curtidas

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

1 curtida

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

6 curtidas

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 curtidas

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 curtidas

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 curtidas

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 curtidas

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 curtidas

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 curtidas