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>