I’m embedding a HubSpot form using v2.js and adding extra CSS inside the form’s iframe by injecting a <style> tag during the onFormReady event. The goal is to preserve HubSpot’s default styles while overriding specific elements (e.g., spacing, submit button styling).
Current approach (simplified):
<div id="hs-form-here"></div>
<script src="https://js.hsforms.net/forms/v2.js" defer></script>
<script>
var CSS_TO_INJECT = [
".hs-form { margin:0 !important; }",
".hs-submit .actions input[type=submit]{ padding:12px 18px; border-radius:6px; }"
].join("\n");
function inject($form, css){
try {
if (!$form || !$form.length) return false;
var doc = $form.get(0).ownerDocument;
if (!doc || !doc.head) return false;
var style = doc.createElement("style");
style.appendChild(doc.createTextNode(css || ""));
doc.head.appendChild(style);
return true;
} catch (e) { return false; }
}
function create(){
if (!window.hbspt || !window.hbspt.forms || !window.hbspt.forms.create) return false;
hbspt.forms.create({
portalId: "242917003",
formId: "a15d8c1d-71c4-4f79-a81a-14124d09ca6a",
region: "na2",
target: "#hs-form-here",
css: "", // keep HubSpot base CSS
cssClass: "im-interested-in",
onFormReady: function($form){
if (!CSS_TO_INJECT) return;
if (inject($form, CSS_TO_INJECT)) return;
var n = 0;
var t = setInterval(function(){
if (inject($form, CSS_TO_INJECT) || ++n > 12) clearInterval(t);
}, 150);
}
});
return true;
}
function whenReady(){
var t = setInterval(function(){
if (create()) clearInterval(t);
}, 100);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", whenReady);
} else {
whenReady();
}
</script>
Issue:
On my public site (www.distributordatasolutions.com, the console shows a 403 Forbidden when v2.js requests: (see image)
https://forms-na2.hsforms.com/embed/v3/form/{portalId}/{formId}
Questions:
- Is injecting CSS into the iframe via onFormReady (adding a <style> tag to the iframe document) a supported/best-practice approach? Any gotchas?
- How do I deal with the 403?
- If i’m on the wriong track, is there another approach I can use?
Any guidance or official documentation links would be greatly appreciated. Thanks!
