简体   繁体   中英

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

只需使用一些Javascript来警告按下后退按钮的人们可能会使用“确定/取消”按钮来破坏他们的交易,还需要一种检测他们是否正在使用任何版本的firefox的方式。

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.

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 )
};

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM