Incorpora commenti di Discourse su un altro sito web tramite Javascript

<div data-theme-toc="true"> </div>

Discourse ha la capacità di incorporare i commenti di un argomento in un sito remoto utilizzando un'API Javascript che crea un IFRAME. Per un esempio di questo in azione, consulta il blog di [Coding Horror](http://blog.codinghorror.com/welcome-to-the-internet-of-compromised-things/#discourse-comments). Il blog è gestito tramite [Ghost](https://ghost.org/) ma i commenti sono incorporati dal suo [forum Discourse](http://discourse.codinghorror.com/t/welcome-to-the-internet-of-compromised-things/3550).

Una cosa importante da notare con questa configurazione è che **gli utenti devono navigare sul tuo forum per pubblicare le risposte**. Questo è intenzionale, poiché riteniamo che l'interfaccia di pubblicazione su un forum Discourse sia attualmente molto più ricca di quanto potremmo incorporare tramite Javascript.

Questa guida mostrerà come configurare l'incorporamento dei commenti sul tuo blog o sito web.

### Come funziona

In Discourse, un argomento è composto da molti post. Quando stai *incorporando* Discourse su un altro sito, stai collegando un documento (voce del blog, pagina HTML, ecc.) con un singolo *argomento*. Quando le persone pubblicano in quell'argomento, i loro commenti appariranno automaticamente nella pagina in cui l'hai incorporato.

Hai la possibilità di far creare automaticamente gli argomenti da Discourse quando viene rilevato un nuovo incorporamento, oppure puoi creare gli argomenti in anticipo tu stesso.

### Configurazione di Discourse per l'incorporamento (configurazione semplice)

La seguente configurazione incorporerà un feed di commenti in una pagina con un URL di blog fittizio di `http://example.com/blog/entry-123.html`, da un forum discourse in esecuzione a `=DISCOURSE=`.

[wrap=placeholder key=DISCOURSE default=discourse.example.com]Dominio per &nbsp;[/wrap]
[wrap=placeholder key=BLOG default=example.com]Dominio per &nbsp;[/wrap]

1. Visita **Admin > Personalizza > Incorporamento** nella tua installazione di Discourse. https://=DISCOURSE=/admin/customize/embedding

2. Crea almeno un **Host Incorporabile** (Embeddable Host). Questo dovrebbe essere il nome host (dominio) in cui desideri incorporare i tuoi commenti. In questo caso, l'host è `=BLOG=` -- nota l'assenza di `http://` e percorso.

    - **Consentire Percorsi** (Path Allowlist) ti consente di specificare i percorsi sull'host remoto che accetterebbero il tuo incorporamento.

   - **Pubblica in Categoria** (Post to Category) - se fornisci una categoria insieme all'host che stai inserendo, i post importati da quell'host finiranno automaticamente in quella categoria. Host diversi possono pubblicare in categorie diverse.

   - **Tag** - puoi assegnare tag da applicare automaticamente agli argomenti creati da un dato host.

   - **Autore Post** (Post Author) - puoi facoltativamente sovrascrivere l'utente di creazione dell'argomento su base per host. Se non impostato, viene utilizzato il valore predefinito dalla scheda **Post e Argomenti** (Posts and Topics).

3. Naviga nella scheda **Post e Argomenti** (Posts and Topics) e compila il campo **Nome utente per la creazione di argomenti** (Username for topic creation). Questo è l'utente che creerà gli argomenti quando verranno trovati nuovi incorporamenti. Supponiamo che il nostro discourse abbia un utente chiamato eviltrout, quindi il valore è `eviltrout`.

4. Inserisci il seguente HTML sulla pagina web all'indirizzo `http://=BLOG=/blog/entry-123.html`

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

Le parti configurabili dello snippet sono nell’oggetto DiscourseEmbed. discourseUrl è il percorso completo alla base del tuo discourse, incluso lo slash finale. discourseEmbedUrl è il documento che sta attualmente incorporando un feed di commenti.

Se imposti correttamente questo, la prima volta che visiti http://=BLOG=/blog/entry-123.html tenterà di caricare i commenti per il post del blog. Poiché non ce ne sono, dirà al forum Discourse di creare un nuovo argomento in background. Un nuovo argomento verrà creato da eviltrout e il contenuto del primo post verrà sottoposto a scansione dal tuo blog e il testo verrà estratto automaticamente.

Una volta creato il nuovo argomento, gli utenti potranno pubblicare su di esso e i loro commenti verranno visualizzati automaticamente la prossima volta che si visiterà http://=BLOG=/blog/entry-123.html.

className è facoltativo e aggiungerà una classe a tua scelta all’incorporamento in modo che tu possa personalizzarlo con CSS.

:bulb: Suggerimento: Se il tuo blog ha più autori, puoi aggiungere un tag <meta name="discourse-username" content="author_username"> a ogni pagina. Quando Discourse esegue la scansione della pagina per creare l’argomento, utilizzerà questo meta tag per determinare l’autore del post, sovrascrivendo il nome utente predefinito impostato nelle impostazioni di amministrazione.

Incorporamento su più di una pagina

Nell’esempio sopra abbiamo codificato l’URL http://=BLOG=/blog/entry-123.html quando abbiamo incorporato lo snippet di Javascript. Di solito questo non sarà sufficiente poiché molti siti hanno molte pagine generate automaticamente. Ad esempio, in un blog, ogni voce ottiene tipicamente la propria pagina. Per supportare ciò, inserisci lo stesso snippet su ogni pagina in cui desideri visualizzare i commenti, ma sostituisci il valore passato a discourseEmbedUrl con l’URL della pagina corrente. Sul mio blog, uso il seguente valore per discourseEmbedUrl: 'http://eviltrout.com<%= current_page.url %>' – man mano che vengono create nuove pagine del blog, nuovi argomenti verranno creati automaticamente su Discourse.

Stile dei contenuti incorporati

Hai la possibilità di aggiungere un foglio di stile per i tuoi commenti incorporati. Utilizza la sezione CSS Incorporato (Embedded CSS) dell’editor Temi in Admin > Personalizza > Temi > [il tuo tema] > Modifica CSS/HTML e puoi aggiungere un foglio di stile personalizzato che verrà servito con i tuoi commenti incorporati. Per impostazione predefinita, pensiamo che il layout sia gradevole su uno sfondo bianco, ma se il tuo sito ha un layout unico, vorrai stilizzarlo tu stesso.

(Facoltativo) Aggiunta di un feed per il polling

Come menzionato sopra, Discourse eseguirà automaticamente la scansione di qualsiasi sito in cui è incorporato. Tuttavia, a volte l’HTML può essere difficile da analizzare e potrebbe non estrarre correttamente il contenuto dei tuoi post. Molti blog e siti web supportano feed RSS/Atom per la syndication, e Discourse può utilizzarlo per estrarre il contenuto dei tuoi post del blog in modo più accurato.

Discourse include il plugin di polling RSS (incluso per impostazione predefinita). Se hai configurato un feed RSS o Atom sul sito in cui stai incorporando Discourse, puoi abilitare l’impostazione del sito rss_polling_enabled e aggiungere l’URL del tuo feed tramite Admin > Plugin > Polling RSS (RSS Polling). Una volta aggiunto l’URL del feed, Discourse analizzerà il feed e pubblicherà i suoi post nella categoria appropriata in base agli Host consentiti che aggiungi alle impostazioni di Incorporamento.

(Configurazione Alternativa) Collegamento ad argomenti esistenti

Alcune persone preferiscono non far creare automaticamente argomenti da Discourse sui loro forum. Preferiscono creare gli argomenti stessi e poi semplicemente dire al loro codice di incorporamento quale argomento vogliono associare. Puoi farlo modificando leggermente il tuo codice di incorporamento:

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

L’unica differenza qui è che abbiamo sostituito discourseEmbedUrl con l’ID di un argomento di Discourse. Se fai questo, nessun argomento verrà creato e i commenti di quell’argomento verranno visualizzati automaticamente.

Impostazione della policy di referrer

A causa dei recenti (settembre 2020) cambiamenti alla policy di referrer predefinita impostata da molti browser, Discourse ora imposta esplicitamente come predefinita la policy di referrer dell’iframe su "no-referrer-when-downgrade". Se, per motivi di sicurezza, il tuo sito richiede una policy di referrer più rigorosa, può essere impostata aggiungendo un valore discourseReferrerPolicy all’oggetto DiscourseEmbed dello script di incorporamento. Per esempio:

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

Interrogazione programmatica dei dettagli di Incorporamento

Abbiamo un endpoint API per interrogare i dettagli di Incorporamento utilizzando embed_url come parametro:

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 la risposta è:

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

Incorporamento di commenti da un sito privato

Per le istanze Discourse private, se Discourse si trova su un sottodominio del dominio del blog, i commenti verranno visualizzati per gli utenti che hanno effettuato l’accesso a Discourse. Gli utenti che non hanno effettuato l’accesso a Discourse vedranno un messaggio di “rifiuto della connessione”. Se Discourse e il blog si trovano su domini completamente separati, non verranno visualizzati commenti per i forum privati.

Risoluzione dei problemi

Il problema più comune che gli utenti riscontrano durante l’incorporamento di Discourse è l’impostazione del valore corretto per gli host incorporabili che hai aggiunto. Assicurati di ricontrollare che sia solo il dominio del tuo sito e che non contenga slash aggiuntivi o caratteri non validi.

116 Mi Piace
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