LoginSignup
0
0

More than 1 year has passed since last update.

Nuxt.js サイトに埋め込んだ HubSpot フォーム が表示されない

Last updated at Posted at 2022-03-29

Vue.js + Nuxt.jsで作成したサイトの問い合わせページに埋め込んだ HubSpot フォームが表示されない問題が起きました。

HubSpot から発行されたコード:
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/shell.js"></script>
<script>
  hbspt.forms.create({
	region: "xxx",
	portalId: "xxxxx",
	formId: "xxxxxxx"
});
</script>
表示されない書き方

Pugを使用したソース:

  • 書き方1
<template lang="pug">
#contact
  h2 お問い合わせ
  #form
    script
      | hbspt.forms.create({
      |   region: "xxx",
      |   portalId: "xxxx",
      |   formId: "xxxxxxx"
      | });
</template>
<script>
export default {
  head () {
    return {
      script: [
        { src: '//js.hsforms.net/forms/shell.js' }
      ]
    }
  },
}
</script>
  • 書き方2
<template lang="pug">
#contact
  h2 お問い合わせ
  #form
    script(src='//js.hsforms.net/forms/shell.js')
    script
      | hbspt.forms.create({
      |   region: "xxx",
      |   portalId: "xxxx",
      |   formId: "xxxxxxx"
      | });
</template>

埋め込んだ直後にはフォームは表示されましたが、ページを更新したりすると表示されなくなりました。
コンソール画面に、"ReferenceError: hbspt is not defined" エラーが表示されました。

原因

Nuxt.js において、フォーム生成スクリプトshell.jsがロードされる前に、shell.jsで定義されたメソッド hbspt.forms.create が先に呼び出されたことが原因でした。

修正方法

shell.jsをロードした後に hbspt.forms.create を呼び出すようにします。

修正後のソース:

<template lang="pug">
#contact
  h2 お問い合わせ
  #form(v-if="isLoaded")
    script
      | hbspt.forms.create({
      |   region: "xxx",
      |   portalId: "xxxx",
      |   formId: "xxxxxxx"
      | });
</template>

<script>
export default {
  data() {
    return {
      isLoaded: false
    };
  },
  head () {
    return {
      script: [
        {
          src: '//js.hsforms.net/forms/shell.js',
          callback: () => { this.isLoaded= true }
        }
      ]
    }
  },
}
</script>
参考になったサイト
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