0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

埋め込んだインスタ記事が表示されない場合の解決法

Last updated at Posted at 2025-02-10

インスタグラムでは、記事にある「埋め込み」をクリックすると以下のようなHTMLが表示され、これを貼り付けることで別のサイトに記事を埋め込めるようになっている。

<blockquote class="instagram-media" data-instgrm-captioned data-instgrm-permalink="https://www.instagram.com/p/xxxxxx/?utm_source=ig_embed&amp;utm_campaign=loading" data-instgrm-version="14" style=" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:540px; min-width:326px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);">
<!-- 省略 -->
</blockquote>
<script async src="//www.instagram.com/embed.js"></script>

しかし、上記タグを貼り付けても、記事が表示されないことがよくある。
原因はJavaScriptのinstgrmオブジェクトがundefinedとなってしまうためであるが、これはscriptタグで外部から取得しているものなのでどうすることもできない。

解決策として、インスタ記事が表示されなかった場合にページをリロードするためのJavaScriptを追加するとよい。
※ instgrmオブジェクトが存在しない場合、URLに?k=0を付加してリロードしている

<script>
document.addEventListener("DOMContentLoaded", () => {
  if (typeof instgrm === "undefined") {
    const url = new URL(window.location.href);
    if (!url.searchParams.has('k')) {
      url.searchParams.set('k', '0');
      window.location.href = url.toString();
    }
  }
});
</script>

詳細は、以下にブログ記事としてまとめてあります。
https://ageo-soft.info/programming_languages/javascript/12631/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?