今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。

有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。

最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。


当前回答

我昨天解决了同样的问题,所以我在这里加上。001。解决方案对我来说很有效至少在主页(index。php)

我希望根文件夹中只有一个文件:index.php。然后我使用文件夹来组织整个项目(代码,css, js等)。所以index.php的代码如下:

<head>
    <title>Please Activate Javascript</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> 
</head>

<body>

<script language="JavaScript">
    $(document).ready(function() {
        location.href = "code/home.php";
    });   
</script>

<noscript>
    <h2>This web site needs javascript activated to work properly. Please activate it. Thanks!</h2>
</noscript>

</body>

</html>

希望这对大家有所帮助。致以最亲切的问候。

其他回答

在meta noscript内部添加刷新不是一个好主意。

因为noscript标签不符合XHTML 属性值“Refresh”是非标准的,不应该使用。“刷新”将页面的控制权从用户手中夺走。使用“刷新”将导致W3C的Web内容可访问性指南失败 ——参考http://www.w3schools.com/TAGS/att_meta_http_equiv.asp。

我认为你可以在noscript标签中插入一个图像标签,并查看你的站点有多少次以及这个图像被加载的频率。

当浏览器中没有启用js时,<noscript>标记中的代码将被执行。 我们可以使用noscript标签来显示msg来打开JS,如下所示。

<noscript>
    <h1 style="text-align: center;">
       To view this page properly, please 
       enable JavaScript and reload the page
    </h1>
</noscript>

同时保持我们的网站内容在身体隐藏。如下

<body>
<div id="main_body" style="display: none;">
    website content.
</div>
</body>

现在如果JS是打开的,你可以让main_body中的内容可见,如下所示

<script type="text/javascript">
    document.getElementById("main_body").style.display="block";
</script>

在某些情况下,倒着做就足够了。使用javascript添加一个类:

// Jquery
$('body').addClass('js-enabled');

/* CSS */
.menu-mobile {display:none;}
body.js-enabled .menu-mobile {display:block;}

这可能会在任何复杂的事情上产生维护问题,但对于某些事情来说,这是一个简单的修复。而不是试图检测它什么时候没有加载,只是根据它加载的时候样式。

Why don't you just put a hijacked onClick() event handler that will fire only when JS is enabled, and use this to append a parameter (js=true) to the clicked/selected URL (you could also detect a drop down list and change the value- of add a hidden form field). So now when the server sees this parameter (js=true) it knows that JS is enabled and then do your fancy logic server-side. The down side to this is that the first time a users comes to your site, bookmark, URL, search engine generated URL- you will need to detect that this is a new user so don't look for the NVP appended into the URL, and the server would have to wait for the next click to determine the user is JS enabled/disabled. Also, another downside is that the URL will end up on the browser URL and if this user then bookmarks this URL it will have the js=true NVP, even if the user does not have JS enabled, though on the next click the server would be wise to knowing whether the user still had JS enabled or not. Sigh.. this is fun...