乐闻世界logo
搜索文章和话题

How to detect if javascript is disabled

3个答案

1
2
3

In HTML pages, if a user's browser has disabled JavaScript, you can use the <noscript> tag to provide an alternative message. For example:

html
<!DOCTYPE html> <html> <head> <title>How to Detect if JavaScript is Enabled</title> </head> <body> <!-- If JavaScript is enabled, the content below will be displayed --> <script type="text/javascript"> document.write("JavaScript is enabled!"); </script> <!-- If JavaScript is disabled, the content within the `<noscript>` tag will be displayed --> <noscript> <p>JavaScript is disabled. Some features of this website may not work properly; please enable JavaScript.</p> // or <meta http-equiv="refresh" content="0; url=whatyouwant.html" /> </noscript> </body> </html>

The example above demonstrates that when JavaScript is disabled, the content within the <noscript> tag is displayed. If JavaScript is enabled, the code inside the <script> tag is executed, and the page shows the message 'JavaScript is enabled!'.

Please note that using the <noscript> tag is merely a simple way to inform users and is not a programmatic detection method. If you need to detect whether JavaScript is disabled on the server side, you typically need to use a fallback method that does not rely on JavaScript, such as determining it through form submissions. This is because without JavaScript support, asynchronous JavaScript requests (e.g., using Ajax) will not occur, and you can only rely on traditional synchronous requests.

2024年6月29日 12:07 回复

This is useful: If JavaScript is disabled, the page redirects visitors.

html
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
2024年6月29日 12:07 回复

I assume you are trying to decide whether to provide JavaScript-enhanced content. The best implementation would employ graceful degradation, ensuring the website remains functional without JavaScript. I also assume you are referring to server-side detection, rather than using the <noscript> element for unexplained reasons.

There is no good way to perform server-side JavaScript detection. As an alternative, you can use JavaScript to set a cookie, then test for that cookie using server-side scripts on subsequent page views. However, this is unsuitable for determining what content to deliver, as it cannot distinguish between visitors without cookies and new visitors or those who do not accept JavaScript cookies.

2024年6月29日 12:07 回复

你的答案