How to submit the form on new tab from iframe?

by cali_green , in category: HTML & CSS , 3 months ago

How to submit the form on new tab from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 3 months ago

@cali_green 

To submit a form in an iframe and open the result in a new tab, you can use JavaScript to target the parent window and open a new tab with the form data. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Get the form element in the iframe
var iframeForm = document.getElementById('myIframe').contentWindow.document.getElementById('myForm');

// Add an event listener to the form submit button
iframeForm.addEventListener('submit', function(event) {
    // Prevent the default form submission
    event.preventDefault();
    
    // Get the form data
    var formData = new FormData(iframeForm);
    
    // Open a new tab with the form data
    var formURL = iframeForm.getAttribute('action');
    var formMethod = iframeForm.getAttribute('method');
    var newTab = window.open('', '_blank');
    newTab.document.write('<html><body><form id="newForm" action="' + formURL + '" method="' + formMethod + '"></form></body></html>');

    formData.forEach(function(value, key) {
        newTab.document.getElementById('newForm').innerHTML += '<input type="hidden" name="' + key + '" value="' + value + '">';
    });

    newTab.document.getElementById('newForm').submit();
});


In this code snippet, replace 'myIframe' with the id of your iframe element, and 'myForm' with the id of your form element inside the iframe. This code listens for the form submission event, prevents the default form submission, collects the form data, and then opens a new tab with the form data set as hidden input elements and submits the form.


Make sure to adjust the code to fit your specific iframe and form elements before using it.