1import { Controller } from '@hotwired/stimulus'; 2 3export default class extends Controller { 4 static values = { 5 portalId: String, 6 formId: String, 7 region: String 8 } 9 10 connect() { 11 this.loadHubSpotScript(); 12 } 13 14 disconnect() { 15 // Clean up the form when navigating away 16 if (this.element) { 17 this.element.innerHTML = ''; 18 } 19 } 20 21 loadHubSpotScript() { 22 // Check if HubSpot script is already loaded 23 if (window.hbspt) { 24 this.createForm(); 25 return; 26 } 27 28 // Check if script is already being loaded 29 const existingScript = document.querySelector('script[src*="js-na2.hsforms.net"]'); 30 if (existingScript) { 31 // Wait for it to load 32 this.waitForHubSpot(); 33 return; 34 } 35 36 // Load the HubSpot script 37 const script = document.createElement('script'); 38 script.src = '//js-na2.hsforms.net/forms/embed/v2.js'; 39 script.charset = 'utf-8'; 40 script.type = 'text/javascript'; 41 script.async = true; 42 43 script.onload = () => { 44 this.waitForHubSpot(); 45 }; 46 47 script.onerror = () => { 48 console.error('Failed to load HubSpot forms script'); 49 }; 50 51 document.head.appendChild(script); 52 } 53 54 waitForHubSpot() { 55 // Poll for hbspt to be available 56 const checkInterval = setInterval(() => { 57 if (window.hbspt && window.hbspt.forms) { 58 clearInterval(checkInterval); 59 this.createForm(); 60 } 61 }, 100); 62 63 // Timeout after 10 seconds 64 setTimeout(() => { 65 clearInterval(checkInterval); 66 if (!window.hbspt) { 67 console.error('HubSpot forms script failed to load within timeout'); 68 } 69 }, 10000); 70 } 71 72 createForm() { 73 if (!window.hbspt || !window.hbspt.forms) { 74 console.error('HubSpot forms not available'); 75 return; 76 } 77 78 try { 79 window.hbspt.forms.create({ 80 portalId: this.portalIdValue, 81 formId: this.formIdValue, 82 region: this.regionValue, 83 target: `#${this.element.id}` 84 }); 85 } catch (error) { 86 console.error('Error creating HubSpot form:', error); 87 } 88 } 89}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.