最近、Blog の AMP 表示テーマを作り始めました。
disqus の コメント欄を AMP の HTML に 組み込む際にやったことを記載します。
disqus の blog に disqus を設置するドメインとは、別ドメインに html を配置、その html を amp-iframe を使い、読み込む方法が、記載されていましたので 実施してみました。
参考
実施したこと
disqus-install-examples/google-amp at master · disqus/disqus-install-examples の How to install の まんまなのですが、
実施したことを記載します。
1. 記載されている HTML をコピーして、用意した HTML 設置用の domain に配置
私は、github.io に配置しました。
kemsakurai.github.io/amp_disqus_thread.html at master · kemsakurai/kemsakurai.github.io
2. コピーした HTML の、s.src = '//EXAMPLE.disqus.com/embed.js';
を自信 の disqus サブドメインに変更。
'//ユーザ名.disqus.com/embed.js'
に変更します。
3. amp-iframe の js リンク と、amp-iframe タグを設置先ドメインに追加。
以下、リンクと、amp-iframe タグを追加しました。
- js リンク
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
- amp-iframe タグ
<amp-iframe width=600 height=200 layout="responsive" sandbox="allow-scripts allow-same-origin allow-modals allow-popups allow-forms" resizable src="https://kemsakurai.github.io/amp_disqus_thread.html#{% disqus_id_for object_for_comments %}"> <div overflow tabindex=0 role=button aria-label="Read more">Read more!</div> </amp-iframe>
<div overflow tabindex=0 role=button aria-label="Read more">Read more!</div>
は、
Example には記載がないですが、amp validator を実行したところエラーが出力されていたので記載しました。
resizable
を指定している場合は、必須で必要なようです。
上記 html は、djagno template で、{% disqus_id_for object_for_comments %}
で、blog 記事ごとの id を生成しています。
4. diaqus の 設定画面から、信頼済みのドメインの追加。
信頼済みドメインとして、github.io と、自ドメインを追加しました。
これで AMP HTML 上で、disqus のコメント欄表示ができるようになります。
5. 追記 page.url と、page.identifier の設定方法を変更した。
後日、気づいたのですが、1.-4.
の設定だけだと、AMP ページと、通常ページ が別ページとして扱われており、コメント欄の情報が共用できていなかったため、以下を修正しました。
-
amp-iframe 呼び出し部の変更
canonical url を iframe に パラメータ url でクエリストリングとして設定、クエリストリングの末尾に、hash を移動しました。
<div id="disqus_thread"> <amp-iframe width=600 height=200 layout="responsive" sandbox="allow-scripts allow-same-origin allow-modals allow-popups allow-forms" resizable src="https://kemsakurai.github.io/cooperation/amp_disqus_thread.html?url={{ request.get_full_path|to_normal_url }}#{% disqus_id_for object_for_comments %}"> <div overflow tabindex=0 role=button aria-label="Read more">Read more!</div> </amp-iframe> </div>
-
iframe html で page.url と、page.identifier を設定
クエリストリングで、設定した url を取得、domain を付与して、page.url とし、hashの#
を削除して、page.identifier として設定しました。
var disqus_config = function () { this.page.url = "https://www.monotalk.xyz" + (new URL(window.location)).searchParams.get("url"); // Replace PAGE_URL with your page's canonical URL variable var hash = window.location.hash; if (hash.length > 0) { hash = hash.slice(1); } this.page.identifier = hash; };
これで、AMP ページでも、通常ページでも同一のコメントが表示されるようになります。
以上です。
コメント