Check whether Javascript is enabled

2019-02-03 18:23发布

Is there a way to check whether Javascript is enabled or supported by the browser? If it's not supported, I would like to redirect the user to a user-friendly error page.

I am using jQuery and the PHP Zend Framework.

9条回答
干净又极端
2楼-- · 2019-02-03 18:36

Whether or not javascript is enabled is only known from within the context of a browser, so the best you can do is write some browser-side code to set a flag based on if javascript is enabled or not. One possibility is do something like

<noscript><img src="/javascript_disabled.php"></noscript>

and

// contents of javascript_disabled.php
$_SESSION['javascript_disabled'] = 1;
查看更多
狗以群分
3楼-- · 2019-02-03 18:43
<noscript><meta http-equiv="refresh" content="1;url=error.html"></noscript>

This will redirect to an error page if script is disabled. Just replace error.html with the URL of your error page.

查看更多
乱世女痞
4楼-- · 2019-02-03 18:44

Piece of cake!

Encompass your entire Javascript page in one DIV.

Overlay a second DIV of equal size that contains your non-Javascript page. Give that DIV an id and a high z-index:

div id="hidejs" style="z-index: 200"

In this second non-JS DIV, have your very first code be Javascript that sets this DIV's visibility to hidden:

document.getElementById.("hidejs").style.visibility = "hidden";

No Javascript enabled? Nothing will happen and they'll see the overlying non-Javascript page.

Javascript enabled? The overlying non-Javascript page will be made invisible and they'll see the underlying Javascript page.

This also lets you keep the whole page in one file, making modifications easier, rather than trying to manage two files for the same page.

查看更多
可以哭但决不认输i
5楼-- · 2019-02-03 18:47

Yes. Make you have the latest jQuery.

Javascript:

$(function(){ $('#jsEnabled2').html('Yes it is') }) 

PHP:

$js - 'No'; 
$jscheck = 'Javascript Enabled: '; 
$jscheck .= '<span id="jsEnabled">'.$js.'</span>';
print $jscheck;
查看更多
不美不萌又怎样
6楼-- · 2019-02-03 18:53

As yet another option, you can (though it requires a second page visit) use javascript to set a cookie.

If the cookie exists server-side (they have javascript) render the page as normal. During the absense of the cookie, you can either use a Location redirect, or render the appropriate [stripped-down] template to accommodate their lack of javascript support.

page html

<script type="text/javascript">
  document.cookie = 'hasJS=true';
</script>

page php

if (isset($_COOKIE['hasJS'])){
  // normal page render
}else{
  header('Location: http://mysite.com/index-nojs.php');
}
查看更多
Anthone
7楼-- · 2019-02-03 18:53

Use <noscript> tags to include a meta-redirect if the page does not have JavaScript.

<noscript> tags are called when the browser connecting to the page does not have JavaScript.

查看更多
登录 后发表回答