My application depends on JavaScript, I want to check the client browser's JavaScript is enabled or not and raise an alert message if its turned off.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- void before promise syntax
- Keeping track of variable instances
There's actually a
<noscript>
tag that you can use to display the content contained inside when javascript is not available.Something like:
The div just won't show if they have javascript, and it's pretty easy to tell if javascript IS working, no matter whether you need it to ping your server back to let it know, or use it to perform some more advanced functions.
"Raise an alert message if its turned off" is paradox, since if it is turned off, you cannot "do" anything programatically.
You can do it the other way 'round, however: make that message appear by default, and have JavaScript hide it if it is turned on (e.g. by setting a DIVs visibility to hidden),
or you rely on the standard compliance of the browser and use the <noscript> tag. Stuff inside the <noscript> gets shown if no javascript is enabled. BTW, make sure to set the type="text/javascript" attribute of the script tag.
See also http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3
Put the message in a
<div>
that's wrapped in a<noscript>
tag. If JavaScript is disabled, the<div>
will be rendered as part of the DOM; if script is enabled, the div won't be in the DOM.For example, you can put the following immediately after the opening
<body>
tag, and style it through CSS to have red background to make it more prominent.A browser may be "JavaScript capable" but that does not mean that JavaScript has not been disabled by the user or by an admin. There is no real way to determine this. Best practices dictate "Progressive Enhancement"; that is, you application needs to work without JavaScript first - then add the JavaScript functionality for those (most) that have it enabled.
http://www.alistapart.com/articles/progressiveenhancementwithjavascript/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/progressive-enhancement.shtml
Avoid hacky solutions to this and bear in mind that there are also accessibility issues for people with screen readers. <noscript> content only displays if JavaScript is disabled. Most screen reader users have JavaScript enabled, so they will see your inaccessible script rather than the <noscript> content.