How to check browser's JavaScript is enabled o

2020-07-11 08:00发布

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.

4条回答
▲ chillily
2楼-- · 2020-07-11 08:16

There's actually a <noscript> tag that you can use to display the content contained inside when javascript is not available.

Something like:

<noscript>
    <div>
        You must enable javascript to continue.
    </div>
</noscript>

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.

查看更多
Luminary・发光体
3楼-- · 2020-07-11 08:21

"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

查看更多
4楼-- · 2020-07-11 08:31

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.

<noscript>
    <div id="js-warning">
        To be able to access all of our features, you need a browser that supports JavaScript, and it needs to be enabled.
    </div>
</noscript>
查看更多
孤傲高冷的网名
5楼-- · 2020-07-11 08:42

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.

查看更多
登录 后发表回答