Disable "Back" & "Refresh" Button in Browser [duplicate] - javascript

I am doing web development.
I have a page to do with credit card, which when user click "refresh" or "Back", the transaction will be performed one more time, which is unwanted.
This include Browser top left "Back" & "Refresh" button, "right click->Refresh/Back", press "F5" key.
This is to be done on certain cgi page only, not all of them.
Can this be done using Javascript? Or any other method?

The standard way is to do it in 3 steps.
the form page submits fields to processing page
processing page processes data and redirects to result page
result page just displays results, reloading it won't do any harm.

This breaks the basic browser user experience model...users should always be able to use the Refresh and Back buttons in their browser. Recommend that you fix your page another way.
If you update your question to include the server language/platform/technology that you are using then someone might be able to suggest a solution.

The simple fact that resubmitting the form generates a duplicate transaction is worrying. You should have some sort of check to ensure each submit of form data is unique.
For example, the page which would submit the form should be given a unique ID that gets submitted with the form. The business logic should then be able to recognise that the form submitted has already been processed (as the (no longer) unique ID will be the same), so ignores the second attempt.
The 'standard way' still doesn't stop clients from clicking the back button twice... or even going back and resubmitting the form if they don't think (for whatever reason) it has been processed.

generate a random string and store it in session,
then output it to your form as a hidden value,
check the submitted and store variable, if matches process your request,
go to 1.

Place this code on the form page
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now-new TimeSpan(1,0,0));
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetAllowResponseInBrowserHistory(false);

You shouldn't try to "block" these actions.
What you should do is make sure that nothing happends when someone "double submits" the form.

and in some browser you can´t even do that, and this is good!

The best way is to have enough session handling logic that you can recognise the 2nd (and onwards) attempt as "this is just a re-submission" and ignore it.

I didn't see this here so here it is.
Put a unique token in the form.
The submit button triggers an xmlhttp(ajax) request to the server to create a session variable named after the token with a stored value of 1.
The ajax request submits the form after receiving a positive state change.
The form processing script checks for the session variable withe the stored value of 1.
The script removes the session variable and processes the form.
If the session variable is not found, the form will not be processed. Since the variable is removed as soon as its found, the form can only be run by pressing the submit button. Refresh and back will not submit the form. This will work without the use of a redirect.

vartec:s solution solves the reload-problem, not the back-problem, so here are a solution to that:
The form page sets a session variable, for example session("fromformpage")=1
The processing page check the session variable, if its ="1" then process data and redirect to result page if any other than ="1" then just redirect to result page.
The result page sets the session variable to "".
Then if the user is pressing back button, the processing page will not do the process again, only redirect to process page.

I found the above Post/Redirect/Get explanations a little ambiguous
Here's what I followed and hopefully it helps someone in the future
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
Essentially the process based on the above solution is:
Submit from the FORM page to the processing page (or to itself)
Handle database or payment processing etc
If required, store user feedback message in a session variable, possible error messages etc
Perform header redirect to results page (or to original form page). If required, display custom message from processing page. Such as "Error Credit Card payment was rejected", and reset session variables.
Redirect with something like:
header("HTTP/1.1 303 See Other");
header("Location: http://$_SERVER[HTTP_HOST]/yourfilehere.php");
die();
The header redirect will initiate a GET request on "yourfilehere.php", because a redirect is simply that, a "request" to fetch data FROM the server, NOT a POST which submits data TO the server. Thus, the redirect/GET prevents any further DB/payments processing occurring after a refresh. The 301 error status will help with back button pressing.
Helpful Reading:
http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
http://www.theserverside.com/news/1365146/Redirect-After-Post
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
https://en.wikipedia.org/wiki/HTTP#Request_methods
http://en.wikipedia.org/wiki/Post/Redirect/Get

Just put this javascript on the html section of aspx page above head section
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
We need to put it on the html section of the page which we want to prevent user to visit by hitting the back button
Complete code of the page looks like this
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</head>
<body onload="disableBackButton()">
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>
If you are using firefox then use instead of onload
If you want to disable back button using code behind of aspx page,than you need to write below mentioned code
C# code behind
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language="javascript">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
We can also achieve this by disabling browser caching or cache by writing this line of code either in Page_load event or in Page_Init event
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Doing this,user will get the page has expired message when hitting back button of browser
Demo is :

This code works for not back from current page me..
Here I put a code which helps you , not open contextmenu and on browser reload ask you leave a page or not...
I am trying the ask click on browser back button
jQuery( document ).ready(function() {
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;
var wasPressed = false;
function fkey(e){
e = e || window.event;
//alert(e.keyCode);
if( wasPressed ) return;
if (e.keyCode == 116 || e.keyCode == 8 || e.keyCode == 17) {
// alert("f5 pressed");
window.onbeforeunload = null;
return true;
}
}
window.onbeforeunload = function (event) {
var message = ''; // Type message here
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
jQuery(function () {
jQuery("a").click(function () {
window.onbeforeunload = null;
});
jQuery(".btn").click(function () {
window.onbeforeunload = null;
});
//Disable part of page
$(document).on("contextmenu",function(e){
return false;
});
});});
Thanks,

Related

How to prevent a php page from browser back button?

I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.
You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.
Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })
Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.
Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>

Redirect to any page and submit form details

I'm looking to submit form details using method="POST" to an external URL, then redirect the user to a 'Thank you' page after successfully completing the form.
My sample HTML/Javascript is as follows, however the page is not redirecting to Google.com as intended. Any help on fixing this would be much appreciated!
HTML:
<form action="externalURLhere" method="post" name="theForm"
id="theForm" style="margin-bottom:0px;padding:2px;background-color:#e0e0e0;" onSubmit="return
MM_validateForm(); return redirect();">
JavaScript:
function MM_validateForm() {
if ( !jQuery('#theForm #FirstName').val() ) {
alert('Please input your first name.');
jQuery('#theForm #FirstName').focus();
return false;
}
if ( !jQuery('#theForm #LastName').val() ) {
alert('Please input your last name.');
jQuery('#theForm #LastName').focus();
return false;
}
if ( !jQuery('#theForm #daytimephone').val() ) {
alert('Please input your phone number.');
jQuery('#theForm #daytimephone').focus();
return false;
}
if ( !jQuery('#theForm #Email').val() ) {
alert('Please input your email.');
jQuery('#theForm #Email').focus();
return false;
}
if ( !jQuery('#theForm #BID').val() ) {
alert('Please select your preferred campus.');
jQuery('#theForm #BID').focus();
return false;
}
if ( !jQuery('#theForm #programs').val() ) {
alert('Please select your preferred program.');
jQuery('#theForm #programs').focus();
return false;
}
if ( !jQuery('#theForm #How_Heard').val() ) {
alert('Please select how you heard about us.');
jQuery('#theForm #How_Heard').focus();
return false;
}
return true;
}
// ]]></script>
<script type="text/javascript">
function redirect() {
window.location = "www.google.com";
return false;
}
</script>
When the user clicks the submit button, onsubmit event occures, and, depending on the return value of the function binded to the event, the form submits (return true) or does not submit (return false);
The function may be binded to the event using HTML:
<form onSubmit="if(/*some validation here*/){return true;} else {return
false;}"></form>
or in javascript script itself:
form1.onsubmit=function(){if(/*some validation here*/){return true;}
else {return false;}}
Generally, it does not matter;
You know, the function's body is executed until the "return" occures. Then it immediatly stops and the return value is passed to the function invoker. So, what you have wrote in the onSubmit="" HTML tag attribute is the equivalent of the following JS code:
form1.onsubmit=function(){
testPassed=validate();
return testPassed;
someValueRedirectFunctionReturns=redirect();
return someValueRedirectFunctionReturns;
}
So, you can see, that no matter if the form data test is passed or not, because your validate() function's return value (true if form is okay and false if user has entered bad data) is immediatly then returned in the event function. So, your redirect() function cannot occur, because the onsubmit event handler function is stopped and the value is returned;
To make this work, you should modify the code:
form1.onsubmit=function(){
if(!validate())
return false; //test failed, form is not passed, no need to redirect to "thank you page".
else
redirect();
}
So, the redirect function will be called if the form validation test is passed. Right here we ran in an another problem.
The only way, if the onsubmit event handler function is defined, to submit the form is to return true; -- return from the function, means stop it and proceed executing from the where it was called. When you change the window.location propterty of the page in the function, redirection occurs immediatly, so the function even do not return; -- JavaScript execution immediatly interrupts, and the new page starts loading -- of course, no data can be passed via form submition;
So, you have to
Submit form (if the data is valid) -- return true;
Somehow redirect (this means, to continue execute your JS code at another page) from the page where the form is submitted.
And... that is not possible.
You can't continue executing the JS code after the form is sent because:
The event handler function has returned. That means it is stopped.
The form is sent, and an another page is now loading. The JS code of the previous page is lost, and cannot be executed anymore.
This means, that you can't affect the behaviour of the page that you are loading (in synchronous mode) from the page, that has started the loading.
And you can't make the new page redirect to the page you want ("thank you" one).
Usual form sending is just loading a new page with additional parameters. E. g. you can't modify the page that a link on your page is following to;
Anyway, there are still several ways to acheive what you want:
If YOU own the page, where the form is submitted, you may just receive the data of the form and immediatly send the redirection header. E. g., via PHP on the server side.If the page IS NOT YOURS (you can't modify neither the server, nor the page, nor anything on the server side), then you have to work with the form in slightly different way(s):Use frames or floating frames, either loading the data into the frame(s) by the javascript code itself, or by loading another page (from the same server on which the form page is located), that you have permission to modify, and modify it. E. g.:In one frame, make a form where the user actually enters data;In another frame, make another form which contains the same fields that the first does, but hidden ones;Do not submit the first form, but pass the data from to the second form, and submit() the second one;Redirect the first frame (or the whole page) to the "thank you" page;The first frame may be even hidden (CSS: display:none) -- that won't affect the functionality.Use AJAX. That is a special technology of making HTTP request (submitting form!) from the javascript code without reloading the actual page. There may be some problems, if you try to send data to the externalURLHere page, if it is not yours. If so, you may create a "router" page on your server, which will receive the data sent by the form and route it to the target, externalURLHere page. Then you may even...Don't use AJAX. Just make the router page (when I say "page", I mostly mean a PHPscript, or another cgi technology), which will also display the "Thank you" HTML document.And so on...
I've tryied to make as complete answer, as possible, I hope it has helped.
P. S. Sorry for my English.
P. P. S. My first answer on Stack Overflow -- I may be doing something wrong, sorry.
It's tough to pin down the exact reason why it isn't working without your full code and more specific requirements.
For instance, if you are submitting to a php file, you can do the redirect in that external php file using:
header('Location: http://www.example.com/');
If you are simply submitting to another html file, you could use Ajax: How to redirect using AJAX?
Try to add protocol
window.location = "http://google.com";

How to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}​
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation

Redirect to another page is causing dup entries

dearest experts.
You helped me with this issue on this link below previousl:
How to I redirect to another page *after* printing document?
Things seemed to be working fine until this morning we discussed that users were submitting duplicate entries.
The reason for this is that once the user clicks to Submit their request,they are presented with a button that says, ">>>Click Here To Print Form<<<<".
Users are required to print this form but for some reason, they forget to do so.
In the event that they forget to print this form, they are taking back to the input screen with boxes still retaining the data they initially entered.
Is there a way to redirec them to results.aspx page, whether they print the form or not?
Please see current code and many thanks in advance.
<script type ="text/javascript">
function doPrint() {
var printContent = document.getElementById("pdmyop");
window.print(printContent);
document.location.href = "results.aspx";
}
</script>
**********************************
<asp:Button ID="btnPrint" runat="server" Text=">>>Click Here To Print Form<<<<" OnClientClick="doPrint(); return false;" />
You can add this script at the end of the SubmitForm procedure:
String script = String.Format("window.print(); window.location = '{0}';", ResolveClientUrl("~/results.aspx"));
ClientScript.RegisterStartupScript(insub.GetType(), "print", script, true);
I hope you can translate this code from C# to VB. If insub placed in an UpdatePanel use ScriptManager instead of the ClientScript.
Be warned, that this code doesn't work in Chrome (as well as any code those make redirect onto different page before document printed)

Detecting javascript during login of an asp.net MVC app...does this code look ok?

My LogIn action originally looked like this:
return new RedirectResult(nameValueCollection["ReturnUrl"]);
But, I would like to know whether the client has JavaScript enabled before the home page loads, so I changed it to this:
return View(new LogInViewModel { ReturnUrl = nameValueCollection["ReturnUrl"] });
And send the following view instead of the instant-redirect:
#model Obr.Web.Models.LogInViewModel
#{
Layout = null;
string noJSReturnUrl = Model.ReturnUrl + (Model.ReturnUrl.Contains("?") ? "&" : "?") + "noJS=true";
}
<!doctype html>
<html>
<head>
<title>Loggin in...</title>
<meta http-equiv="REFRESH" content="1;url=#noJSReturnUrl">
<script type="text/javascript">
window.location = "#Model.ReturnUrl";
</script>
</head>
<body>
<noscript>
Loggin in...<br />
Click here if you are not redirected promptly.
</noscript>
</body>
</html>
The idea is that if the user does not have JavaScript enabled, they see a brief loading message, and the home page loads after a second. If JavaScript is enabled, the page reloads instantly. In the future I could even post to the server the dimensions of the viewport and such.
Does this look like it would work? If the window.location command takes longer than a second to run, will it be interrupted by the meta refresh, or does it block that refresh? I am hoping the latter, so I don't need to increase the delay for those non-js people.
I figure my new way adds a little extra weight to the payload of the redirect, but it's not an extra round-trip or anything, is it? The redirect happens anyway, does it not?
Update: I neglected to mention a very important point. I do not actually have control over the login screen itself, only the page it posts to. This code is part of a product that relies on an external authentication mechanism.
You do not need the extra redirect just to detect javascript. On the original form where the user logs in, create a hidden form element javaScriptEnabled with a default value of false. Then use JavaScript to set the value to true. Then you can read this value in the handler. If it's true, then JS is enabled.
No extra page needed.
Since you can't change the original login form then your solution looks good. It won't display anything to the user who has JS and should look just like another redirect, with just an extra hop.
Once you write a new url to window.location then the browser will stop processing the current page's js and timers and everything and simply move on to retrieving/processing the next page.

Categories