Home > Mobile >  How do you run JS code after form submission and subsequest page redirect?
How do you run JS code after form submission and subsequest page redirect?

Time:01-07

I have a form in HTML like so:

<form action="/home.html" method="post" name="loginForm" target="_top" id="login-form" onsubmit="func(this);"></form>

This form, when submitted, will change the current webpage to /home.html. What I want to do is to execute specific JS code, only known to the webpage which the form is on, after the webpage is changed. How would I go about doing that?

CodePudding user response:

Because JavaScript execution does not persist across different loaded documents, you won't be able to do this from the origin page alone. You'll need to put all the JavaScript functionality you want into a script file that home.html includes.

If you need to pass variables from the origin page to the /home page, you can either include them in the <form> so your backend can echo them to the new destination page, or include them as query parameters that the destination page parses and uses.

CodePudding user response:

I figured out a way to do this. Create an named iframe, and then set the target attribute of the form element to the name of the iframe. Make the iframe fullscreen, then you effectively are able to do what I requested, since, when the form submits, the response will be put into the iframe instead of the overall tab, and the original page will have execution privileges. Note that this only works if the iframe has the same origin as the parent.

  •  Tags:  
  • Related