結論
iframe.contentWindow
から twttr
オブジェクトを見つけて、event.bind("rendered", () => {})
の第二引数に、表示処理を書くことです。
iframe.addEventListener("load", () => iframe.contentWindow.twttr.events.bind("rendered", () => iframe.setAttribute("style", "opacity: 1;") ) );
背景
https://twitter.com/openwc/status/1427617679427440643
のような URL から、埋め込みコンテンツをブログサイトなどに表示したいです。
https://publish.twitter.com/oembed?url=${URL}
のレスポンスの中の html が、埋め込みコンテンツになります。
これを iframe の srcdoc に設定することで、埋め込みコンテンツを表示することができます。
<iframe></iframe>
/* const url = "https://twitter.com/openwc/status/1427617679427440643"; const oembedUrl = `https://publish.twitter.com/oembed?url=${url}`; // response.html of `fetch(oembedUrl)` is html. */ const html = '<blockquote class="twitter-tweet"><p lang="en" dir="ltr">`npm init @<200c>open-wc` now supports lit v2!<br><br>Give it a try and let us know what you think<a href="https://t.co/9191LFIYHZ">https://t.co/9191LFIYHZ</a></p>— Open Web Components (@OpenWc) <a href="https://twitter.com/OpenWc/status/1427617679427440643?ref_src=twsrc%5Etfw">August 17, 2021</a></blockquote>\n<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>\n'; const iframe = document.querySelector("iframe"); iframe.setAttribute("srcdoc", html);
課題
iframe で srcdoc を読み込んだ後、埋め込みたい Tweet の文字列だけが、チラっと見えてしまいます。
下の例であれば、npm init @open-wc now supports lit v2!
がチラっと見えるはずです。reload をしてみると分かります。
チラっと見えてしまうのを阻止したいです。
解決
埋め込みコンテンツの描画後イベント rendered
というものがあります。これを使います。
https://developer.twitter.com/en/docs/twitter-for-websites/javascript-api/guides/javascript-api
実装の順番は、次のとおりです。
- iframe から、
load
イベントを検知 iframe.contentWindow
から、twttr
オブジェクトを見つけるtwttr.events.bind("rendered", () => {})
で、描画後の処理を書く
実際に、コードを書くと、次のとおりです。
/* const url = "https://twitter.com/openwc/status/1427617679427440643"; const oembedUrl = `https://publish.twitter.com/oembed?url=${url}`; // response.html of `fetch(oembedUrl)` is html. */ const html = '<blockquote class="twitter-tweet"><p lang="en" dir="ltr">`npm init @<200c>open-wc` now supports lit v2!<br><br>Give it a try and let us know what you think<a href="https://t.co/9191LFIYHZ">https://t.co/9191LFIYHZ</a></p>— Open Web Components (@OpenWc) <a href="https://twitter.com/OpenWc/status/1427617679427440643?ref_src=twsrc%5Etfw">August 17, 2021</a></blockquote>\n<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>\n'; const iframe = document.querySelector("iframe"); iframe.addEventListener("load", () => iframe.contentWindow.twttr.events.bind("rendered", () => iframe.setAttribute("style", "opacity: 1;") ) ); iframe.setAttribute("srcdoc", html);
html は、style
で隠しておきます。(手段は問いません)
<iframe style="opacity: 0;"></iframe>
解決した結果が、こちらです。
npm init @open-wc now supports lit v2!
のチラっとが見えなくなっているはずです。