0

I've got a form on a page that I would like to force submission on when a user tries to refresh the page. Is this possible?

JS

window.onbeforeunload = function(event) { document.getElementById('userpass').submit(); }

HTML

<form style="position:relative; width:100%" id="userpass" action="savestarter.php" method="post">
<input style="display:none" type="text" name="username" value=<?php echo '"' . $_POST["username"] . '"'?> />
</form>
Kaylub
  • 91
  • 1
  • 1
  • 8
  • `window.onbeforeunload = function(event){}`? – Professor Abronsius Jan 12 '18 at 08:20
  • I tried this: window.onbeforeunload = function(event) { document.getElementById('formname').submit(); } but it seems to ignore the "document.getElementById('formname').submit();" Maybe I'm missing something simple? – Kaylub Jan 12 '18 at 08:21
  • Add some example code to show what you've already tried and edit to be more specific.. – lewiatan Jan 12 '18 at 08:24
  • 3
    Possible duplicate of [Execute function before refresh](https://stackoverflow.com/questions/9308336/execute-function-before-refresh) – Kuldip Solanki Jan 12 '18 at 08:26
  • These solutions all fall short. Doesn't work in firefox, doesn't work in chrome, doesn't ever force a form submission. – Kaylub Jan 12 '18 at 08:34
  • `onbeforeunload` can only be used to show a confirmation message, not to execute your own arbitrary code. What you want could possibly be abused to do stuff harmful to the user, therefor it is not possible. You could use `onbeforeunload` to _warn_ the user that they might lose unsaved changes or something like that, and let them cancel the navigation away from the page. But anything more than that - sorry, nope, _my_ browser, there for none of _your_ business. – CBroe Jan 12 '18 at 10:18
  • Yea, exactly. I think I'm going to use cookies to solve my problem and just warn the user that they must have cookies enabled. Then I can bypass the java function on reload if the user reloads. – Kaylub Jan 12 '18 at 18:20

1 Answers1

-1

Yes, it is possible.

window.onbeforeunload = function(event)
{
    return confirm("Confirm refresh");
};
Pang
  • 9,564
  • 146
  • 81
  • 122
  • This simply asks for a confirmation to the refresh, but doesn't force the form to submit. Am I missing something simple? – Kaylub Jan 12 '18 at 08:28
  • These solutions all fall short. Doesn't work in firefox, doesn't work in chrome, doesn't ever force a form submission. Could you explain this approach a bit more for me? – Kaylub Jan 12 '18 at 08:34