Eskay Amadeus
Eskay Amadeus

Reputation: 318

How do you prevent a user from cancelling a page redirect?

I have a line of code:

location.href = 'payments/basic.php';

It works fine, but a user can simply press the Esc key to cancel the operation. I tried to use an event listener to prevent the Esc key from being pressed, but it only works while the user is on the initial page. As soon as they are being redirected, it stops working and they can quickly press the Esc key or the big X beside the address bar in their browser to cancel the redirect.

Is there a way I can completely prevent that?

Edit: The reason I want to do this is that upon login, they are automatically sent to the index page. I have a flag in my DB which checks if a user has made payment. And then on the index page, I have a little script that queries the DB to check if the flag is true or false. If it's false, they are immediately notified that they are being redirected to make their payment. If at this point of redirection, they cancel, they will be able to remain on the Index page without payment.

Upvotes: 0

Views: 334

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370789

I think the only way to prevent the Esc key from stopping navigation is to not navigate away from the original page at all. Instead of doing

location.href = 'payments/basic.php';

make an XHR or fetch request to basic.php, and populate the current document with the results, instead of loading an entirely new document - just like how a SPA works.

(You will almost certainly want to make some changes to basic.php - eg, have it return easily-parseable JSON containing the data to populate the page with instead of an HTML document)

Regarding the edit

upon login, they are automatically sent to the index page

If at this point of redirection, they cancel, they will be able to remain on the Index page without payment.

If you're trying to prevent access the the original page, then just don't serve the original page until you've checked the flag in the database. Don't serve the index page to begin with until you've validated the user's credentials. If they aren't authorized, redirect them in PHP (not in JS) to the payments page. No need to mess with the user's escape key.

Upvotes: 2

Lyndon
Lyndon

Reputation: 301

Why not do it the other way around? Default to the payment page, if payment is already made, then redirect to index. lol.

Upvotes: 1

Related Questions