Home > OS >  embedded form by repeated script
embedded form by repeated script

Time:10-06

I am adding a Hubspot embedded form to a page, the form is added by script. I use an onMounted so that when the form is displayed and it does it well, the problem is that, when I leave that component where the form is and re-enter, it adds another space to the form which does not have any input, it only occupies the space and below it, it already adds the correct form, how can I solve this? Tried unUnmonted and conditionals, but failed to resolve. This is the code where I add the form:

onMounted(() => {
      let script = document.createElement('script')
      script.setAttribute('src', 'https://js.hsforms.net/forms/v2.js')

      document.head.appendChild(script)

      script.addEventListener("load", () => {
          if (window.hbspt) {
              window.hbspt.forms.create({
                  region: "",
                  portalId: "423423423",
                  formId: "65363456-456-23g22-3423-g34g3f363g",
                  target: "#content-form"
              });

          }
      })
  })

this is what it leaves me in the HTML, the first iframe is empty but it occupies the space enter image description here

CodePudding user response:

The solution that worked was a variation on the full answer below i.e. all that was required is:

onMounted(() => {
    document.querySelector('#content-form>iframe")?.remove();
    ... rest of code unchanged
});

Here's a guess

rewrite onMounted to load the script only once

onMounted(() => {
      const loadForm = () => {
          window.hbspt.forms.create({
              region: "",
              portalId: "423423423",
              formId: "65363456-456-23g22-3423-g34g3f363g",
              target: "#content-form"
          });
      };
      if (window.hbspt) { // script already loaded
          return loadForm();
      }
      let script = document.createElement('script');
      script.src = 'https://js.hsforms.net/forms/v2.js';

      document.head.appendChild(script);

      script.addEventListener("load", () => {
          if (window.hbspt) {
              loadForm();
          }
      });
});

onUnmounted should just remove the content of the target element

onUnmounted(() => {
    document.querySelector('#content-form>iframe")?.remove();
});

As an alternative, if you load https://js.hsforms.net/forms/v2.js in your index.html instead, then onMounted only needs

onMounted(() => {
    window.hbspt.forms.create({
        region: "",
        portalId: "423423423",
        formId: "65363456-456-23g22-3423-g34g3f363g",
        target: "#content-form"
    });
});

and onUnmounted would remain the same

  • Related