Filling Input field using js

I'm trying to fill the hidden input field in hubspot form
<input name="last_visited_url_before_demo" class="hs-input" type="hidden" value="">
<input name="last_visited_url_before_demo" class="hs-input" type="hidden" value="">
tried using this code
document.addEventListener('DOMContentLoaded', function() {
const inputField = document.querySelector('.hs_last_visited_url_before_demo input');
const url = "theurl.com";
inputField.value = url;
});
document.addEventListener('DOMContentLoaded', function() {
const inputField = document.querySelector('.hs_last_visited_url_before_demo input');
const url = "theurl.com";
inputField.value = url;
});
Codepen: https://codepen.io/Abdul-Ahad-the-decoder/pen/KKYYyod?editors=1010 i'm not sure, what's going wrong here, can you please help
5 Replies
Jochem
Jochem7mo ago
the hsform is inserting an iframe and loading the form in that. document.querySelector can't go into that iframe you can try selecting the iframe using querySelector, then stepping in using, then using contentDocument instead but that only works in some circumstances depending on the iframe's site's crossorigin policy
Mannix
Mannix7mo ago
also DOMContentLoaded will run before the iframe is loaded if im not mistaken
Jochem
Jochem7mo ago
it unrelated to the iframe loading at the very least if there's a slow image and a fast iframe site, it might work, but it might also not the load event should wait to fire until the iframe is done loading. Won't solve this issue though
Abdul Ahad⚡
Abdul Ahad⚡OP7mo ago
window.addEventListener('load', function() {
const iframe = document.querySelector('iframe[src*="hubspot"]');
if (iframe) {
iframe.addEventListener('load', function() {
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const inputField = iframeDocument.querySelector('.hs_last_visited_url_before_demo input');
if (inputField) {
const url = "theurl.com";
inputField.value = url;
}
});
}
});
window.addEventListener('load', function() {
const iframe = document.querySelector('iframe[src*="hubspot"]');
if (iframe) {
iframe.addEventListener('load', function() {
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const inputField = iframeDocument.querySelector('.hs_last_visited_url_before_demo input');
if (inputField) {
const url = "theurl.com";
inputField.value = url;
}
});
}
});
tried using contentDocument, still not able to get it, maybe due to the crossorigin policy then. any other way I can try?
Jochem
Jochem7mo ago
probably not, unless hsforms provides a way to send data into the form using the contructor thing in the html in your codepen
Want results from more Discord servers?
Add your server