Incrustar comentarios de Discourse en otro sitio web mediante Javascript

{“content”: “\u003cdiv data-theme-toc="true"\u003e \u003c/div\u003e\n\nDiscourse tiene la capacidad de incrustar los comentarios de un tema en un sitio remoto utilizando una API de Javascript que crea un IFRAME. Para un ejemplo de esto en acción, consulta el blog de Coding Horror. El blog se ejecuta a través de Ghost pero los comentarios se incrustan desde su foro de Discourse.\n\nAlgo importante a tener en cuenta con esta configuración es que los usuarios deben navegar a tu foro para publicar respuestas. Esto es intencional, ya que creemos que la interfaz de publicación en un foro de Discourse es actualmente mucho más rica de lo que podríamos incrustar a través de Javascript.\n\nEsta guía te mostrará cómo configurar la incrustación de comentarios en tu propio blog o sitio web.\n\n### Cómo funciona\n\nEn Discourse, un tema se compone de muchas publicaciones. Cuando estás incrustando Discourse en otro sitio, estás vinculando un documento (entrada de blog, página HTML, etc.) con un único tema. Cuando las personas publican en ese tema, sus comentarios aparecerán automáticamente en la página donde lo incrustaste.\n\nTienes la opción de hacer que Discourse cree los temas automáticamente cuando se encuentre una nueva incrustación, o puedes crear los temas tú mismo con anticipación.\n\n### Configuración de Discourse para la incrustación (configuración simple)\n\nLa siguiente configuración incrustará un feed de comentarios en una página con la URL de un blog falso de http://example.com/blog/entry-123.html, desde un foro de Discourse que se ejecuta en =DISCOURSE=.\n\nDominio para \u0026nbsp;\nDominio para \u0026nbsp;\n\n1. Visita Admin \u0026gt; Personalizar \u0026gt; Incrustación en tu instalación de Discourse. https://=DISCOURSE=/admin/customize/embedding\n\n2. Crea al menos un Host Incrustable. Este debería ser el nombre de host (dominio) donde deseas incrustar tus comentarios. En este caso, el host es =BLOG= – ten en cuenta la ausencia de http:// y la ruta.\n\n - Lista de permisos de ruta te permite especificar las rutas en el host remoto que aceptarían tu incrustación.\n\n - Publicar en categoría - si proporcionas una categoría junto con el host que estás ingresando, las publicaciones importadas de ese host terminarán automáticamente en esa categoría. Diferentes hosts pueden publicar en diferentes categorías.\n\n - Etiquetas - puedes asignar etiquetas para que se apliquen automáticamente a los temas creados a partir de un host determinado.\n\n - Autor de la publicación - puedes anular opcionalmente el usuario creador del tema por host. Si no se establece, se utiliza el valor predeterminado de la pestaña Publicaciones y temas.\n \n3. Navega a la pestaña Publicaciones y temas y rellena el campo Nombre de usuario para la creación de temas. Este es el usuario que creará temas cuando se encuentren nuevas incrustaciones. Supongamos que nuestro discourse tiene un usuario llamado eviltrout, por lo que el valor es eviltrout.\n\n4. Inserta el siguiente HTML en la página web en http://=BLOG=/blog/entry-123.html\n\nhtml\n\u003cdiv id='discourse-comments'\u003e\u003c/div\u003e\n\n\u003cscript type=\"text/javascript\"\u003e\n DiscourseEmbed = {\n discourseUrl: 'https://discourse.example.com/',\n discourseEmbedUrl: 'http://example.com/blog/entry-123.html',\n // className: 'CLASS_NAME',\n };\n\n (function() {\n var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;\n d.src = DiscourseEmbed.discourseUrl + 'javascripts/embed.js';\n (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);\n })();\n\u003c/script\u003e\n\n\nLas partes configurables del fragmento están en el objeto DiscourseEmbed. discourseUrl es la ruta completa a la base de tu discourse, incluida la barra inclinada final. discourseEmbedUrl es el documento que actualmente incrusta un feed de comentarios.\n\nSi configuras esto correctamente, la primera vez que visites http://=BLOG=/blog/entry-123.html, intentará cargar comentarios para la publicación del blog. Como no hay ninguno, le indicará al foro de Discourse que cree un nuevo tema en segundo plano. eviltrout creará un nuevo tema y el contenido de la primera publicación se rastreará desde tu blog y el texto se extraerá automáticamente.\n\nUna vez que se crea el nuevo tema, los usuarios pueden publicar en él y sus comentarios se mostrarán automáticamente la próxima vez que se visite http://=BLOG=/blog/entry-123.html.\n\nclassName es opcional y agregará una clase de tu elección a la incrustación para que puedas personalizarla con CSS.\n\n\u003e :bulb: Consejo: Si tu blog tiene varios autores, puedes agregar una etiqueta \u003cmeta name=\"discourse-username\" content=\"author_username\"\u003e a cada página. Cuando Discourse rastree la página para crear el tema, utilizará esta etiqueta meta para determinar el autor de la publicación, anulando el nombre de usuario predeterminado establecido en la configuración de administración.\n\n### Incrustación en más de una página\n\nEn el ejemplo anterior codificamos nuestra URL http://=BLOG=/blog/entry-123.html al incrustar el fragmento de Javascript. Esto generalmente no será suficiente, ya que muchos sitios tienen muchas páginas que se generan automáticamente. Por ejemplo, en un blog, cada entrada normalmente tiene su propia página. Para admitir esto, coloca el mismo fragmento en cada página donde desees mostrar comentarios, pero reemplaza el valor pasado a discourseEmbedUrl con la URL de la página actual. En mi blog, utilizo el siguiente valor para discourseEmbedUrl: 'http://eviltrout.com\u003c%= current_page.url %\u003e' – a medida que se crean nuevas páginas de blog, se crearán nuevos temas para ellas automáticamente en Discourse.\n\n### Estilizando tu contenido incrustado\n\nTienes la capacidad de agregar una hoja de estilo para tus comentarios incrustados. Usa la sección CSS Incrustado del editor de temas en Admin \u003e Personalizar \u003e Temas \u003e [tu tema] \u003e Editar CSS/HTML y puedes agregar una hoja de estilo personalizada que se servirá con tus comentarios incrustados. Por defecto, pensamos que el diseño se ve bien en un fondo blanco, pero si tu sitio tiene un diseño único, querrás estilizarlo tú mismo.\n\n### (Opcional) Agregar un feed para sondeo\n\nComo se mencionó anteriormente, Discourse rastreará automáticamente cualquier sitio en el que esté incrustado. Sin embargo, a veces el HTML puede ser difícil de analizar y es posible que no extraiga el contenido de tus publicaciones correctamente. Muchos blogs y sitios web admiten feeds RSS/Atom para sindicación, y Discourse puede usar esto para extraer el contenido de tus publicaciones de blog con mayor precisión.\n\nDiscourse incluye el plugin de sondeo RSS (incluido por defecto). Si tienes configurado un feed RSS o Atom en el sitio en el que estás incrustando Discourse, puedes habilitar la configuración del sitio rss_polling_enabled y agregar la URL de tu feed a través de Admin \u003e Plugins \u003e Sondeo RSS. Una vez que se haya agregado la URL del feed, Discourse analizará el feed y publicará sus publicaciones en la categoría apropiada según los Hosts Permitidos que agregues a tu configuración de Incrustación.\n\n### (Configuración alternativa) Vinculación a temas existentes\n\nA algunas personas prefieren no hacer que Discourse cree temas automáticamente en sus foros. Les gustaría crear los temas ellos mismos y luego simplemente indicarle a su código de incrustación qué tema quieren asociar. Puedes hacer esto cambiando ligeramente tu código de incrustación:\n\nhtml\n\u003cdiv id='discourse-comments'\u003e\u003c/div\u003e\n\n\u003cscript type=\"text/javascript\"\u003e\n window.DiscourseEmbed = {\n discourseUrl: 'https://=DISCOURSE=/',\n topicId: 12345\n };\n\n (function() {\n var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;\n d.src = window.DiscourseEmbed.discourseUrl + 'javascripts/embed.js';\n (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);\n })();\n\u003c/script\u003e\n\n\nLa única diferencia aquí es que hemos reemplazado discourseEmbedUrl con el ID de un tema de Discourse. Si haces esto, no se creará ningún tema y los comentarios de ese tema se mostrarán automáticamente.\n\n### Establecer la política de remitente\n\nDebido a los recientes cambios (septiembre de 2020) en la política de remitente predeterminada que establecen muchos navegadores, Discourse ahora establece explícitamente la política de remitente del iframe en \"no-referrer-when-downgrade\". Si, por razones de seguridad, tu sitio requiere una política de remitente más estricta, se puede establecer agregando un valor discourseReferrerPolicy al objeto DiscourseEmbed del script de incrustación. Por ejemplo:\n\njs\nDiscourseEmbed = { discourseUrl: 'https://forum.example.com/',\n discourseEmbedUrl: '\u003cyour_posts_canonical_URL\u003e',\n discourseReferrerPolicy: 'strict-origin-when-cross-origin'};\n\n\n### Consulta programática de los detalles de la incrustación\n\nTeneos un endpoint de API para consultar los detalles de la incrustación utilizando la embed_url como parámetro:\n\n\ncurl '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' \n\n\nY la respuesta es:\n\njson\n{\n \"topic_id\": 187794,\n \"post_id\": 925017,\n \"topic_slug\": \"discourse-team-grows-to-50-blog\",\n \"comment_count\": 2\n}\n\n\n### Incrustación de comentarios desde un sitio privado\n\nPara las instancias privadas de Discourse, si Discourse está en un subdominio del dominio del blog, los comentarios se mostrarán a los usuarios que hayan iniciado sesión en Discourse. Los usuarios que no hayan iniciado sesión en Discourse verán un mensaje de ‘se negó a conectarse’. Si Discourse y el blog están en dominios completamente separados, no se mostrarán comentarios para los foros privados.\n\n### Solución de problemas\n\nEl problema más común que tienen los usuarios al incrustar Discourse es establecer el valor correcto para los hosts incrustables que agregaron. Asegúrate de verificar dos veces que sea solo el dominio de tu sitio y que no contenga barras adicionales ni caracteres no válidos.”}

116 Me gusta
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 Me gusta

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

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

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

1 me gusta

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

6 Me gusta

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

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

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

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

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

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