11

How can I submit a form to a third-party website without it causing the page to reload (i.e. in the background)?

For some background, I'm trying to programmatically log a user into their google account in the background.

I can programmatically log them in using the following:

var div = document.createElement("div");
div.innerHTML = FORM_HTML;
var form = div.getElementsByTagName("form")[0];
form.action = "https://www.google.com/accounts/ServiceLoginAuth";
form.GALX.value = FORM_GALX; // dynamically obtained using AJAX
form.Email.value = USER_EMAIL;
form.Passwd.value = USER_PASSWORD;
form.submit();

This logs me in and opens up my Google dashboard. How can I prevent form.action from redirecting me?

Please note that this div is never actually added to a document, which is preferable but not required.

4
  • Tongue-in-cheek answer: This can be done through a method known as cross-site scripting. owasp.org/index.php/Cross-site_Scripting_%28XSS%29 Yeah, I believe his intention is not malicious, but just the same.
    – David
    Jul 29, 2011 at 19:03
  • 2
    @David — No, that's CSRF not XSS
    – Quentin
    Jul 29, 2011 at 19:16
  • @Quentin - that's right. Thanks for the correction!
    – David
    Jul 29, 2011 at 20:05
  • Actually, I'm pretty sure that this method wouldn't even work from a webpage (since google has CSRF protection to avoid malicious tracking); this is being run from a Chrome Extension (which means it isn't technically CSRF). Jul 29, 2011 at 21:08

3 Answers 3

18

you can set the target to submit the form to an IFRAME
like that

<form target="transFrame" method="POST" action="http://...."  ></form>
<iframe style="" name="transFrame" id="transFrame"></iframe>
2
  • Actually I have a follow-up to this. When I post to an iframe, how can I register when the server has responded? onload="alert('load');" doesn't work and the iframe's contents never seem to change. Jul 29, 2011 at 21:34
  • @alex c, I know how to do it in jQuery: $('#transFrame').ready(function () {alert("loaded")});
    – fatnjazzy
    Jul 30, 2011 at 4:11
1

You need to use AJAX to generate XMLHttpRequest best using any popular JS library such as jQuery, Prototype JS or Mootools.

2
  • Problem, its a cross site request
    – fatnjazzy
    Jul 29, 2011 at 19:06
  • you can use an opaque fetch request to receive only basic data about a request. works cross-site.
    – RedGuy11
    Aug 18, 2021 at 15:44
0

you can use ajax or jquery for request to submit form in background if you want to submit form to secure connection i think they want allow submit form in this way..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.