NibblyPig
NibblyPig

Reputation: 52952

How do I add an alert when the user tries to press the back button or is using firefox? (Javascript)

Just need a little bit of Javascript to warn people that press the back button that it might screw up their transaction with an Ok/Cancel button, and also a way of detecting if they are using any version of firefox.

Upvotes: 0

Views: 1050

Answers (4)

bobince
bobince

Reputation: 536715

Both back-breaking and UA-sniffing are a huge code smell.

A properly-coded web application should not “screw up” when the user goes back a step in a transaction. If it does, you probably have a collection of concurrency problems which will make your site unpleasant to use.

UA-sniffing is highly troublesome, prone to false positives and negatives and, if done on the server end, proxy problems. What is the reason you want to detect Firefox? If you are trying to work around a particular Firefox problem there is almost certainly a better approach focusing on that one feature rather than trying to detect a particular browser.

Upvotes: 1

Ryan Lynch
Ryan Lynch

Reputation: 7786

As to your browser detection question, I don't really like using user agent based browser detection, its better to do feature testing onLoad. But if you are just looking to see if someone is using (or says they are using) Firefox, you can parse the useragent string. Here is an example of this from the jQuery 1.3.2 source:

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
    safari: /webkit/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

Upvotes: 2

Jamie Dixon
Jamie Dixon

Reputation: 54021

This SO question: Detecting Back Button/Hash Change in URL will answer most of your question.

Detecting the back button is a tricky business because it's the same behaviour as closing the window.

You can use the onbeforeunload event handler to handle this but like i say, it's a bit tricky.

Upvotes: 1

fresskoma
fresskoma

Reputation: 25791

You could use something like http://www.sajithmr.me/warning-before-navigate-away-from-a-page/ in order to check if a user is about to leave the page. I'm not sure if there is a solution to target the back-button specifically.

Upvotes: 2

Related Questions