How to detect if JavaScript is disabled?
Asked Answered
M

41

707

There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled.

Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled.

Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.

Mesentery answered 23/9, 2008 at 14:7 Comment(5)
What do you want to do with this information? It could change the answer you get - e.g. progressive enhancement should generally be favoured over trying to detect JavaScript being disabled and taking specific action based on that.Quianaquibble
progressive enhancement is what I am looking for. I want ot be able to redirect them to alternate content that will function properly in the abscence of a JS enable or capable browser.Mesentery
@expiredninja This post from Nicholas Zakas says about 2%, though it is over a year old.Emeryemesis
The easiest way is to use noscript to show non javascript site, and use javascript to show any javascript depend elements by modifying style display.Germanous
enable-javascript.comFelicefelicia
R
309

I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason.

There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.

Royden answered 23/9, 2008 at 14:7 Comment(11)
<noscript> IS the most semanticly accurate way to specify non-javascript content - and rather then detecting if javascript is disabled, detect if it's enabled. So show the "you need javascript to properly use my site" message by default, but hide it with a javascript function immediately onLoad.Betthel
@matt lohkamp: Or even hide the message by default, and put a <style> block inside the <noscript> to unhide (no reflow there if JS enabled). Surprisingly, this works in all modern browsers, and even in IE6Getraer
@matt - I was doing this for a while, but the message stays up for a while on slow connections leaving users confused. I'm here looking for a different solution. @Piskvor - the <noscript> tag in the header will not validate, and a <style> tag in the body will not validate.Carliecarlile
Yeah, that would be an issue if it's outside of a <noscript> tag, right. You mention <noscript> in the header - do you want to conditionally include files depending on whether javascript is turned on?Betthel
...except why are you concerned with validation? Are you validating just to validate? It may not be "correct" but if it works and accomplishes it "with a little dirt under the hood" what's the issue? Don't worry, I won't judge ;-)Lucifer
It stays valid if you just use the style attribute to the given elements within the <noscript> tags (like <noscript><div style="color:red;">blahblah</div></noscript> or sg. similar). BUT it also stays valid if you put the <style> BLOCK normally in the header defining the style of some .noscript (or similar) classed elements, and in the body, within the <noscript> tags, you just give the given elements the previously defined .noscript class, like this: <noscript><div class="noscript">blahblah</div></noscript>Bergerac
@Marc Gear posts: There isn't a good way to perform server-side JavaScript detection. Instead, use JavaScript to set a cookie, and then test for that cookie using server-side scripting upon subsequent page views; deliver content appropriately. But if Javascript is disabled how this can work?Sarajane
@Pispirulito If javascript is disabled, the cookie won't be set and the server, detecting its absence, will serve a non-js version of the page. If the javascript is enabled, the cookie will be set and the server, detecting its presence, will serve a js version of the page. The undesired side effect of this approach is that users who disable cookies will be served non-js versions even if javascript is enabled.Weig
@Steve you dont need <noscript> in the header nor a <style> tag in the body, or any other inline css. simply put your noscript element into the body, insert an html element inside and give it an id or class and control its behaviour via your css style file. validates just fine. for example: <noscript><div id="noScript"><h1>This Site depends on Javascript, so please enable it.</h1></div></noscript>Gardy
As @Weig pointed out, if JavaScript is enabled but the user is blocking cookies non-JS content will be served. It's better to use an AJAX call to a server-side routine that sets a session variable instead. If there's JavaScript, then the AJAX will go through, if not, it won't. This still won't solve the problem of a user logging in with javascript enabled and then disabling it though.Manumit
Actually, the undesired side effects of this approach are possibly even worse. The cookie wouldn't be there on the first page request. You'd have to force the client to refresh after the page fully loaded in order to finally detect the cookie.Coenurus
M
396

I'd like to add my .02 here. It's not 100% bulletproof, but I think it's good enough.

The problem, for me, with the preferred example of putting up some sort of "this site doesn't work so well without Javascript" message is that you then need to make sure that your site works okay without Javascript. And once you've started down that road, then you start realizing that the site should be bulletproof with JS turned off, and that's a whole big chunk of additional work.

So, what you really want is a "redirection" to a page that says "turn on JS, silly". But, of course, you can't reliably do meta redirections. So, here's the suggestion:

<noscript>
    <style type="text/css">
        .pagecontainer {display:none;}
    </style>
    <div class="noscriptmsg">
    You don't have javascript enabled.  Good luck with that.
    </div>
</noscript>

...where all of the content in your site is wrapped with a div of class "pagecontainer". The CSS inside the noscript tag will then hide all of your page content, and instead display whatever "no JS" message you want to show. This is actually what Gmail appears to do...and if it's good enough for Google, it's good enough for my little site.

Musing answered 23/9, 2008 at 14:7 Comment(18)
(9 minutes later) However, it won't validate. Well, points for originality anyway.Carliecarlile
@steve ever try to validate google.com? validation just determines how close the document follows the spec sheet, it in no way effects the usability of the page.Ryals
I don't like the idea of forcing the user to enable javascript. What if he just isn't able to ? I think unobtrusive Javascript is the way to go in almost all cases of public web sites.Dissimilate
@JonasGeiregat What's wrong with forcing the user to require Javascript if your web app was built - and requires - Javascript to function? I hear this comment too often, yet it's only valid for the most simple of sites. Try Facebook without JS and see what happens. If your app was built FOR Javascript, then what's wrong with requiring what 99% of users have enabled anyway?Awry
this is far from a valid approach if you're dealing with controls that rely on javascript. (take a registration form for example). you're able to disable css in most browsers.Woodham
A better solution would be to separate the style block: this should be in the head section. @Steve, now it will validate :)Ribosome
How would this affect search engine crawlers? Would they not see any of the content?Theurer
+1 I like this approach, it's not only constructive for the user but also quick and simple to implement without refactoring a bunch of code. I'd rather have a constructive message than having to wonder why x isn't working..Carmella
@Lee hits it on the nail, you can only do so much for the user before you draw the line on what you will support. We expect all users to have an internet enabled device, should I also implement a paper version of my site for those that refuse to access the internet?Bergh
@Kolors, I made that comment back in Mar 2012, and I'd argue that it's doubly-true today. Since then, we've had Meteor, Angular.Js, Famo.us, and a ton of amazing libraries that all require Javascript to even start. I do wonder what users who choose to disable JS are actually trying to achieve... clearly, they're not surfing the same web as the rest of us, and there's no reason a company should need to scale down their website for the tiniest sub-set of stubborn users...Awry
@elliot: Hmm...I forget the details! How embarrassing. (-; But I do know that meta redirects have to be in the header, which means it may be too far upstream for your page to detect whether JS is enabled or not. I recognize this is not the most helpful reply.Musing
Yeah, and I wondered why I couldn’t upvote your answer, since I forgot to activate my JS :-)) I like and implement your solution! Thanks!Cotten
I presume I'd almost never, ever want a redirection page that says turn on JS, silly. Especially not for detecting whether it's already enabled...Courtland
@Lee doing without JS where it is possible shrinks the javascript's overall complexity, and it's complexitiy is where unethical things tend to hide. Facebook is a great example of being unethical and try pushing the world to follow. If you are determined and able to go the hard way for the good of your heart, then unobtrusive javascript can help on the web to you find your way.Courtland
@naxa - I'm confused by your comment. What "unethical" things are Facebook trying to hide, and how does this relate to having Javascript enabled or not?Awry
Facebook actually functions also without js, but you're told to go to the mobile-enhanced version (or turn js on). As for "who doesn't use js", there's quite a few, actually. First and foremost, people with limited data-connections might turn off js, people who appreciate their phones working more than a couple hours (js-processing is one of the major power drains on cellphones online), not to mention the security-concious among us, with noscript-extensions in the browser and such. Of course, these people are advanced enough to know how to turn it on if they want to use the service.Metacarpal
Worked great for me, just needed to add style-src 'self' 'sha256-dapbzoBUpMY09sH855CMpiVFzV9xGciiPGiUTeyf/gA=' to my Content-Security-Policy in order to allow inline scripting.Kenya
This is a great solution, and exactly what I was looking for. I have a bunch of WebGL demos online and I wanted an easy way to show something if they had JS disabled since "degradation" isn't possible. Loved the line about "If it's good enough for Google" lolKamin
R
309

I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason.

There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.

Royden answered 23/9, 2008 at 14:7 Comment(11)
<noscript> IS the most semanticly accurate way to specify non-javascript content - and rather then detecting if javascript is disabled, detect if it's enabled. So show the "you need javascript to properly use my site" message by default, but hide it with a javascript function immediately onLoad.Betthel
@matt lohkamp: Or even hide the message by default, and put a <style> block inside the <noscript> to unhide (no reflow there if JS enabled). Surprisingly, this works in all modern browsers, and even in IE6Getraer
@matt - I was doing this for a while, but the message stays up for a while on slow connections leaving users confused. I'm here looking for a different solution. @Piskvor - the <noscript> tag in the header will not validate, and a <style> tag in the body will not validate.Carliecarlile
Yeah, that would be an issue if it's outside of a <noscript> tag, right. You mention <noscript> in the header - do you want to conditionally include files depending on whether javascript is turned on?Betthel
...except why are you concerned with validation? Are you validating just to validate? It may not be "correct" but if it works and accomplishes it "with a little dirt under the hood" what's the issue? Don't worry, I won't judge ;-)Lucifer
It stays valid if you just use the style attribute to the given elements within the <noscript> tags (like <noscript><div style="color:red;">blahblah</div></noscript> or sg. similar). BUT it also stays valid if you put the <style> BLOCK normally in the header defining the style of some .noscript (or similar) classed elements, and in the body, within the <noscript> tags, you just give the given elements the previously defined .noscript class, like this: <noscript><div class="noscript">blahblah</div></noscript>Bergerac
@Marc Gear posts: There isn't a good way to perform server-side JavaScript detection. Instead, use JavaScript to set a cookie, and then test for that cookie using server-side scripting upon subsequent page views; deliver content appropriately. But if Javascript is disabled how this can work?Sarajane
@Pispirulito If javascript is disabled, the cookie won't be set and the server, detecting its absence, will serve a non-js version of the page. If the javascript is enabled, the cookie will be set and the server, detecting its presence, will serve a js version of the page. The undesired side effect of this approach is that users who disable cookies will be served non-js versions even if javascript is enabled.Weig
@Steve you dont need <noscript> in the header nor a <style> tag in the body, or any other inline css. simply put your noscript element into the body, insert an html element inside and give it an id or class and control its behaviour via your css style file. validates just fine. for example: <noscript><div id="noScript"><h1>This Site depends on Javascript, so please enable it.</h1></div></noscript>Gardy
As @Weig pointed out, if JavaScript is enabled but the user is blocking cookies non-JS content will be served. It's better to use an AJAX call to a server-side routine that sets a session variable instead. If there's JavaScript, then the AJAX will go through, if not, it won't. This still won't solve the problem of a user logging in with javascript enabled and then disabling it though.Manumit
Actually, the undesired side effects of this approach are possibly even worse. The cookie wouldn't be there on the first page request. You'd have to force the client to refresh after the page fully loaded in order to finally detect the cookie.Coenurus
E
204

noscript blocks are executed when JavaScript is disabled, and are typically used to display alternative content to that you've generated in JavaScript, e.g.

<script type="javascript">
    ... construction of ajaxy-link,  setting of "js-enabled" cookie flag, etc..
</script>
<noscript>
    <a href="next_page.php?nojs=1">Next Page</a>
</noscript>

Users without js will get the next_page link - you can add parameters here so that you know on the next page whether they've come via a JS/non-JS link, or attempt to set a cookie via JS, the absence of which implies JS is disabled. Both of these examples are fairly trivial and open to manipulation, but you get the idea.

If you want a purely statistical idea of how many of your users have javascript disabled, you could do something like:

<noscript>
    <img src="no_js.gif" alt="Javascript not enabled" />
</noscript>

then check your access logs to see how many times this image has been hit. A slightly crude solution, but it'll give you a good idea percentage-wise for your user base.

The above approach (image tracking) won't work well for text-only browsers or those that don't support js at all, so if your userbase swings primarily towards that area, this mightn't be the best approach.

Elongate answered 23/9, 2008 at 14:7 Comment(6)
This isn't very effective. For example, it won't count anybody with text-only browsers, which normally don't have JavaScript support. At the very least, you should disable caching for that image.Magalimagallanes
Would browsere which don't support JS at all not simply ignore the noscript tag and show the image?Companionship
@LKM: Depends on how they're written, most likely they would, so you'd make it a 1x1px dot. That option is mainly for tracking usage patterns server-side, so would still be ok, as it is triggered by a user without javascript capability.Elongate
Note that there is currently a bug with IE8 and the noscript tag if you style it... see positioniseverything.net/explorer.htmlOffload
also you can serve that image as a server-side script, setting the mime-type, and use that to log some information about the user or drop a cookie... px.sklar.com/code.html/id=256Ryals
brilliant. so easy! kicking myself for not knowing this before. However, I just wanted the user to be aware that the site will need javascript to run properly, so a simple <p> tag inside the <noscript> did the trick for me.Lifeanddeath
U
50

This is what worked for me: it redirects a visitor if javascript is disabled

<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
Unsparing answered 23/9, 2008 at 14:7 Comment(6)
This is invalid. noscript elements cannot contain meta elements. I would not trust this to work reliably in all browsers (including future browsers which you cannot currently test in), as they may perform error recovery in different ways.Oneself
This may be invalid, but look at Facebook's code, it uses the same solution in the <head> part - which doesn't mean it's a very good solution, because Facebook's code is far from a valid code, BUT it can mean that it works on many users' browser, which can be an important aspect. But it's true that it's not really suggested. This is their code: <noscript> <meta http-equiv=refresh content="0; URL=/about/messages/?_fb_noscript=1" /> </noscript>Bergerac
IE9 (at least) has a setting "allow META REFRESH". I don't seem many turning it off, but presumably those that don't like javascript do, but if you want 100%, it's not this.Untie
It is valid in HTML5.Reclamation
Edit: XML close was added.Reclamation
This destroys the link when trying to share on Linkedin, we found the hard way... this is not a good idea. Since linkedin follows the meta refresh, disregarding Og tags, etc.Ligneous
P
49

I'd suggest you go the other way around by writing unobtrusive JavaScript.

Make the features of your project work for users with JavaScript disabled, and when you're done, implement your JavaScript UI-enhancements.

https://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Priestridden answered 23/9, 2008 at 14:7 Comment(10)
I'm writing a web-app that displays a list of up to several thousand elements, each with multiple statuses. Considering how poorly <form> would probably go with this, your suggestion isn't always an option.Souther
Life's too short. It's 2012- Enable javascript or go homeMukerji
"Life's too short. It's 2012 - Enable javascript or go home!" is perfect little message to display in the event of no JS. logged in just to tell you that @MukerjiTheotheobald
I also just logged in to say that is AWESOME! @Yarin. I'm making a small site that won't be generally public (consider like an intranet but for friends getting together to work on a project). I'm making it an SPA and not bothering to put in a fallback. Unobtrusive JavaScript would nearly double the workload I'm putting into the SPA concept. With modern javascript libraries such as Knockout, Jquery, among others, we just have to accept that not every site can be easily made "unobtrusive." Javascript is the future of the web.Heliogravure
What if JavaScript IS the feature of the page? I have a couple of pages that use javascipt to animate the user-interactive graphics: no javascript, no content.Latoshalatouche
@Yarin, using javascript where it could be done without it grows the js complexity and unfortunately that is where all the unethical things try to hide. Using javascript only if there is no other way may be the hard and more ethical way. Now you may or may not care about this, but by any means you could leave a perfectly valid answer be on it's own right.Courtland
@Mukerji I build PHP / JS apps for a living I never ever put in fallbacks... if it doesn't work for someone they contact me and I tell them to stop living in the past and enable JS.Poorhouse
@Courtland - Unethical things hide in all code, in every device, whether server or client side. Its not codes fault, its humans fault. I find a campaign against JS ironic because you still use a 3rd party ISP to connect to the internet, still use a computer with 3rd party hardware/firmware, still use insecure cell networks accessible by 3rd party injects, still own a cell phone that uses a 3rd party unpatched OS, still use a flat screen TV that uses a 3rd party wide open update service, etc etc. You are always a victim of MITM-ish channels regardless of whether you turn JS off in your browser.Benempt
@Benempt Hmm, So you have no critical filters or you are just complaining that n611x007 has them placed so far from yours you think they are not the same thing. Still I bet you have more than one password and am wondering why? Different people have different thresholds for privacy and security issues, someone said "Life's too short" and I agree, accept others may be different.Weston
Good Answer. You should still care about your fellow citizens that use screen readers, text-only browsers, etc. Is life too short for that too? Also, there are places and moments where people have to to use Tor and disable javascript. Progressive Enhancement is a thing.Flagitious
S
44

If your use case is that you have a form (e.g., a login form) and your server-side script needs to know if the user has JavaScript enabled, you can do something like this:

<form onsubmit="this.js_enabled.value=1;return true;">
    <input type="hidden" name="js_enabled" value="0">
    <input type="submit" value="go">
</form>

This will change the value of js_enabled to 1 before submitting the form. If your server-side script gets a 0, no JS. If it gets a 1, JS!

Stemson answered 23/9, 2008 at 14:7 Comment(0)
Y
40

<noscript> isn't even necessary, and not to mention not supported in XHTML.

Working Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
    <title>My website</title>
    <style>
      #site {
          display: none;
      }
    </style>
    <script src="http://code.jquery.com/jquery-latest.min.js "></script>
    <script>
      $(document).ready(function() {
          $("#noJS").hide();
          $("#site").show();
      });
    </script>
</head>
<body>
    <div id="noJS">Please enable JavaScript...</div>
    <div id="site">JavaScript dependent content here...</div>
</body>
</html>

In this example, if JavaScript is enabled, then you see the site. If not, then you see the "Please enable JavaScript" message. The best way to test if JavaScript is enabled, is to simply try and use JavaScript! If it works, it's enabled, if not, then it's not...

Yorick answered 23/9, 2008 at 14:7 Comment(2)
Ha, XHTML. Those were the days... Things have changed a lot: developer.mozilla.org/en-US/docs/Web/HTML/Element/noscriptVegetation
@StephanWeinhold, JSF uses XHTML.Incommodious
D
36

Use a .no-js class on the body and create non javascript styles based on .no-js parent class. If javascript is disabled you will get all the non javascript styles, if there is JS support the .no-js class will be replaced giving you all the styles as usual.

 document.body.className = document.body.className.replace("no-js","js");

trick used in HTML5 boilerplate http://html5boilerplate.com/ through modernizr but you can use one line of javascript to replace the classes

noscript tags are okay but why have extra stuff in your html when it can be done with css

Dich answered 23/9, 2008 at 14:7 Comment(1)
Cannot believe it took this long before someone mentioned the .nojs class! This is one of the most seamless approaches and puts noscript to shame.Estheresthesia
S
16

just a bit tough but (hairbo gave me the idea)

CSS:

.pagecontainer {
  display: none;
}

JS:

function load() {
  document.getElementById('noscriptmsg').style.display = "none";
  document.getElementById('load').style.display = "block";
  /* rest of js*/
}

HTML:

<body onload="load();">

  <div class="pagecontainer" id="load">
    Page loading....
  </div>
  <div id="noscriptmsg">
    You don't have javascript enabled. Good luck with that.
  </div>

</body>

would work in any case right? even if the noscript tag is unsupported (only some css required) any one knows a non css solution?

Sinusoidal answered 23/9, 2008 at 14:7 Comment(0)
U
13

Because I always want to give the browser something worthwhile to look at I often use this trick:

First, any portion of a page that needs JavaScript to run properly (including passive HTML elements that get modified through getElementById calls etc.) are designed to be usable as-is with the assumption that there ISN'T javaScript available. (designed as if it wasn't there)

Any elements that would require JavaScript, I place inside a tag something like:

<span name="jsOnly" style="display: none;"></span>

Then at the beginning of my document, I use .onload or document.ready within a loop of getElementsByName('jsOnly') to set the .style.display = ""; turning the JS dependent elements back on. That way, non-JS browsers don't ever have to see the JS dependent portions of the site, and if they have it, it appears immediately when it's ready.

Once you are used to this method, it's fairly easy to hybridize your code to handle both situations, although I am only now experimenting with the noscript tag and expect it will have some additional advantages.

Unprofitable answered 23/9, 2008 at 14:7 Comment(0)
D
13

You'll want to take a look at the noscript tag.

<script type="text/javascript">
...some javascript script to insert data...
</script>
<noscript>
   <p>Access the <a href="http://someplace.com/data">data.</a></p>
</noscript>
Dugan answered 23/9, 2008 at 14:7 Comment(0)
B
13

You can use a simple JS snippet to set the value of a hidden field. When posted back you know if JS was enabled or not.

Or you can try to open a popup window that you close rapidly (but that might be visible).

Also you have the NOSCRIPT tag that you can use to show text for browsers with JS disabled.

Bloem answered 23/9, 2008 at 14:7 Comment(3)
This is not a good answer. The first solution requires a page reload and a form submission. The second solution opens a popup (ack!) and closes it "rapidly" - from the client side? -1Carliecarlile
Sometimes you need to know server side if a site has JS enabled or not, so I don't see how you can do it other than posting something back. Agree that a popup is ugly nad I'm not really sure about this but it should be possible to open a popup outside the visible area of the screen so the user is not disturbed by this. No elegant but it works and there's no page reload.Bloem
Spambots also posts to a hidden field.Jannette
B
12

Add this to the HEAD tag of each page.

<noscript>
        <meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>

So you have:

<head>
    <noscript>
        <meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
    </noscript>
</head>

With thanks to Jay.

Bridgid answered 23/9, 2008 at 14:7 Comment(0)
S
12

The noscript tag works well, but will require each additional page request to continue serving useless JS files, since essentially noscript is a client side check.

You could set a cookie with JS, but as someone else pointed out, this could fail. Ideally, you'd like to be able to detect JS client side, and without using cookies, set a session server side for that user that indicates is JS is enabled.

A possibility is to dynamically add a 1x1 image using JavaScript where the src attribute is actually a server side script. All this script does is saves to the current user session that JS is enabled ($_SESSION['js_enabled']). You can then output a 1x1 blank image back to the browser. The script won't run for users who have JS disabled, and hence the $_SESSION['js_enabled'] won't be set. Then for further pages served to this user, you can decide whether to include all of your external JS files, but you'll always want to include the check, since some of your users might be using the NoScript Firefox add-on or have JS disabled temporarily for some other reason.

You'll probably want to include this check somewhere close to the end of your page so that the additional HTTP request doesn't slow down the rendering of your page.

Suricate answered 23/9, 2008 at 14:7 Comment(0)
R
11

A common solution is to the meta tag in conjunction with noscript to refresh the page and notify the server when JavaScript is disabled, like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <noscript>
            <meta http-equiv="refresh" content="0; /?javascript=false">
        </noscript>
        <meta charset="UTF-8"/>
        <title></title>
    </head>
</html>

In the above example when JavaScript is disabled the browser will redirect to the home page of the web site in 0 seconds. In addition it will also send the parameter javascript=false to the server.

A server side script such as node.js or PHP can then parse the parameter and come to know that JavaScript is disabled. It can then send a special non-JavaScript version of the web site to the client.

Rixdollar answered 23/9, 2008 at 14:7 Comment(1)
But, if javascript is disabled, then this will loop forever?Wilding
U
10

This is the "cleanest" solution id use:

<noscript>
    <style>
        body *{ /*hides all elements inside the body*/
            display: none;
        }
        h1{ /* even if this h1 is inside head tags it will be first hidden, so we have to display it again after all body elements are hidden*/
            display: block;
        }
    </style>
    <h1>JavaScript is not enabled, please check your browser settings.</h1>
</noscript>
Undermost answered 23/9, 2008 at 14:7 Comment(0)
G
9

If javascript is disabled your client-side code won't run anyway, so I assume you mean you want that info available server-side. In that case, noscript is less helpful. Instead, I'd have a hidden input and use javascript to fill in a value. After your next request or postback, if the value is there you know javascript is turned on.

Be careful of things like noscript, where the first request may show javascript disabled, but future requests turn it on.

Grain answered 23/9, 2008 at 14:7 Comment(0)
P
5

You might, for instance, use something like document.location = 'java_page.html' to redirect the browser to a new, script-laden page. Failure to redirect implies that JavaScript is unavailable, in which case you can either resort to CGI ro utines or insert appropriate code between the tags. (NOTE: NOSCRIPT is only available in Netscape Navigator 3.0 and up.)

credit http://www.intranetjournal.com/faqs/jsfaq/how12.html

Polik answered 23/9, 2008 at 14:7 Comment(0)
R
4

code inside <noscript> tags will be executed when there is no js enabled in browser. we can use noscript tags to display msg to turn on JS as below.

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

while keeping our website content inside body as hidden. as below

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

now if JS is turned on you can just make the content inside your main_body visible as below

<script type="text/javascript">
    document.getElementById("main_body").style.display="block";
</script>
Roundly answered 23/9, 2008 at 14:7 Comment(0)
G
4

People have already posted examples that are good options for detection, but based on your requirement of "give warning that the site is not able to function properly without the browser having JS enabled". You basically add an element that appears somehow on the page, for example the 'pop-ups' on Stack Overflow when you earn a badge, with an appropriate message, then remove this with some Javascript that runs as soon as the page is loaded (and I mean the DOM, not the whole page).

Gumboil answered 23/9, 2008 at 14:7 Comment(0)
T
4

I think you could insert an image tag into a noscript tag and look at the stats how many times your site and how often this image has been loaded.

Tao answered 23/9, 2008 at 14:7 Comment(0)
F
4

A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!

Fm answered 23/9, 2008 at 14:7 Comment(0)
D
3

I've figured out another approach using css and javascript itself.
This is just to start tinkering with classes and ids.

The CSS snippet:
1. Create a css ID rule, and name it #jsDis.
2. Use the "content" property to generate a text after the BODY element. (You can style this as you wish).
3 Create a 2nd css ID rule and name it #jsEn, and stylize it. (for the sake of simplicity, I gave to my #jsEn rule a different background color.

<style>
#jsDis:after {
    content:"Javascript is Disable. Please turn it ON!";
    font:bold 11px Verdana;
    color:#FF0000;
}

#jsEn {
    background-color:#dedede;
}

#jsEn:after {
    content:"Javascript is Enable. Well Done!";
    font:bold 11px Verdana;
    color:#333333;
}
</style>

The JavaScript snippet:
1. Create a function.
2. Grab the BODY ID with getElementById and assign it to a variable.
3. Using the JS function 'setAttribute', change the value of the ID attribute of the BODY element.

<script>
function jsOn() {
    var chgID = document.getElementById('jsDis');
    chgID.setAttribute('id', 'jsEn');
}
</script>

The HTML part.
1. Name the BODY element attribute with the ID of #jsDis.
2. Add the onLoad event with the function name. (jsOn()).

<body id="jsDis" onLoad="jsOn()">

Because of the BODY tag has been given the ID of #jsDis:
- If Javascript is enable, it will change by himself the attribute of the BODY tag.
- If Javascript is disable, it will show the css 'content:' rule text.

You can play around with a #wrapper container, or with any DIV that use JS.

Hope this helps to get the idea.

Dwaindwaine answered 23/9, 2008 at 14:7 Comment(0)
T
3

I would like to add my solution to get reliable statistics on how many real users visit my site with javascript disabled over the total users. The check is done one time only per session with these benefits:

  • Users visiting 100 pages or just 1 are counted 1 each. This allows to focus on single users, not pages.
  • Does not break page flow, structure or semantic in anyway
  • Could logs user agent. This allow to exclude bots from statistics, such as google bot and bing bot which usually have JS disabled! Could also log IP, time etc...
  • Just one check per session (minimal overload)

My code uses PHP, mysql and jquery with ajax but could be adapted to other languanges:

Create a table in your DB like this one:

CREATE TABLE IF NOT EXISTS `log_JS` (
  `logJS_id` int(11) NOT NULL AUTO_INCREMENT,
  `data_ins` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `session_id` varchar(50) NOT NULL,
  `JS_ON` tinyint(1) NOT NULL DEFAULT '0',
  `agent` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`logJS_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

Add this to every page after using session_start() or equivalent (jquery required):

<?  if (!isset($_SESSION["JSTest"]))
    { 
        mysql_query("INSERT INTO log_JS (session_id, agent) VALUES ('" . mysql_real_escape_string(session_id()) . "', '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']). "')"); 
        $_SESSION["JSTest"] = 1; // One time per session
        ?>
        <script type="text/javascript">
            $(document).ready(function() { $.get('JSOK.php'); });
        </script>
        <?
    }
?>

Create the page JSOK.php like this:

<?
include_once("[DB connection file].php");   
mysql_query("UPDATE log_JS SET JS_ON = 1 WHERE session_id = '" . mysql_real_escape_string(session_id()) . "'");
Takin answered 23/9, 2008 at 14:7 Comment(0)
W
3

In some cases, doing it backwards could be sufficient. Add a class using javascript:

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

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

This could create maintenance issues on anything complex, but it's a simple fix for some things. Rather than trying to detect when it's not loaded, just style according to when it is loaded.

Woodall answered 23/9, 2008 at 14:7 Comment(0)
H
3

Check for cookies using a pure server side solution i have introduced here then check for javascript by dropping a cookie using Jquery.Cookie and then check for cookie this way u check for both cookies and javascript

Hbomb answered 23/9, 2008 at 14:7 Comment(0)
A
3

You don't detect whether the user has javascript disabled (server side or client). Instead, you assume that javascript is disabled and build your webpage with javascript disabled. This obviates the need for noscript, which you should avoid using anyway because it doesn't work quite right and is unnecessary.

For example, just build your site to say <div id="nojs">This website doesn't work without JS</div>

Then, your script will simply do document.getElementById('nojs').style.display = 'none'; and go about its normal JS business.

Aras answered 23/9, 2008 at 14:7 Comment(1)
this is a great seamless approach <noscript> tags are much harder to maintain on different pages with this approach you can maintain your noscript styling through your css file.Ureide
B
3

To force users to enable JavaScripts, I set 'href' attribute of each link to the same document, which notifies user to enable JavaScripts or download Firefox (if they don't know how to enable JavaScripts). I stored actual link url to the 'name' attribute of links and defined a global onclick event that reads 'name' attribute and redirects the page there.

This works well for my user-base, though a bit fascist ;).

Bumbailiff answered 23/9, 2008 at 14:7 Comment(2)
and a bit annoying if the user does have JS enabled and clicks on the link before your progressive javascript kicks in...Nylon
Sure, but no issue reported yet.Bumbailiff
S
3

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...

Sabrasabre answered 23/9, 2008 at 14:7 Comment(0)
A
2

For those who just want to track if js was enabled, how about using an ajax routine to store the state? For example, I log all visitors/visits in a set of tables. The JSenabled field can be set to a default of FALSE, and the ajax routine would set it to TRUE, if JS is enabled.

Ankle answered 23/9, 2008 at 14:7 Comment(1)
Your answer is very sloppy and not thought through. There are major problems with this proposition, none of which you addressed. Using JS to check if JS is enabled immediately seems suspicious. Even assuming that you can identify a user in the visitors table when they have JS turned off (cookies + web beacons come to mind, but's it's unreliable), you'll have a problem in case: 1. user visits with JS on 2. same user visits with JS off.Sourwood
E
2

Adding a refresh in meta inside noscript is not a good idea.

  1. Because noscript tag is not XHTML compliant

  2. The attribute value "Refresh" is nonstandard, and should not be used. "Refresh" takes the control of a page away from the user. Using "Refresh" will cause a failure in W3C's Web Content Accessibility Guidelines --- Reference http://www.w3schools.com/TAGS/att_meta_http_equiv.asp.

Enfold answered 23/9, 2008 at 14:7 Comment(2)
No one said anything about XHTML. <noscript> is perfectly valid HTML 4.01 strict.Zeena
noscript is also perfectly valid in XHTML 1.0 and XHTML 1.1. It can't contain meta elements, and it should be avoided in favour of progressive enhancement, but it is part of the languages.Oneself
E
2

Detect it in what? JavaScript? That would be impossible. If you just want it for logging purposes, you could use some sort of tracking scheme, where each page has JavaScript that will make a request for a special resource (probably a very small gif or similar). That way you can just take the difference between unique page requests and requests for your tracking file.

Erich answered 23/9, 2008 at 14:7 Comment(0)
D
1

Update 2022

This question has already over 30 answers, but none of them seem to be clear or precise on what had to be done.

  • Server Side Framework Used - ASP.NET Core
  • Client side - vanilla js

On BaseController where the first entry point on the app which is OnActionExecutionAsync I have this piece of logic.

  • Basically by default I assume client does not have javascript enabled and set this flag.
Response.Cookies.Append("jsEnabled", "false");
  • Now after initial load on client I have a javascript function that updates this flag to true.
  • This function will only have run when the environment has javascript

So the full solution is here.

Client

On Initial load add this function

function detectIfJavascriptIsEnabled() {
    // if this function run's which means js is enabled
    var jsEnabled = getCookie('jsEnabled');
    if (jsEnabled === 'false') {
        setCookie('jsEnabled', 'true');
        location.reload();
    }
}

Server

private bool ValidateIfEnvironmentHasJavascript() {
  if (HttpContext.Request.Cookies != null && HttpContext.Request.Cookies.Count > 0) {
    Boolean.TryParse(HttpContext.Request.Cookies["jsEnabled"], out
      var hasJavascriptEnabled);
    return hasJavascriptEnabled;
  } else {
    Response.Cookies.Append("jsEnabled", "false",
      new CookieOptions() {
        IsEssential = true, Expires = DateTime.UtcNow.AddHours(24)
      });
  }

  return false;
}

This is how you get the result

var environmentHasJavascript = ValidateIfEnvironmentHasJavascript();
Doorplate answered 23/9, 2008 at 14:7 Comment(0)
C
1

Why do you need to know server-side if JavaScript is enabled? Does it matter which variant the browser supports? Does it e.g. need to understand keyword let or is just var okay?

I'd recommend sending readable content that doesn't require any JavaScript to be accessible and then just try to load JS file to add all the JS behaviors you want in addition.

For example, the UI might end up missing Login or Modify button if JS is not enabled and it might include a small text at the bottom (using <noscript> or some element with CSS animation that shows the text after a small delay if JS code doesn't remove the whole element soon enough) saying "To login/modify this content, you must enable JavaScript support in your browser." If you do this well, the reader may not even notice that anything is missing unless he or she is trying to login or modify the content.

As an optimization you could then set cookie with JavaScript and the server could avoid sending the non-JavaScript readable content if you wish to acquire it asyncronously for some reason. Just make sure to only set this cookie after the JS code has run into completion at least once, instead of setting it immediately the JS code starts to run, to make sure that the end user doesn't end up with a blank screen when (not if!) the JS code fails for any reason.

(Note that loading the initial page state asyncronous will not get that content to end user any faster. However, you could only send part of the total content without JavaScript. That could allow rendering "above the fold" faster and then asyncronously load rest of the page using JS code.)

As an added bonus, search engines can still index your site without any JavaScript enabled.

Cuttlefish answered 23/9, 2008 at 14:7 Comment(0)
A
1

Of course, Cookies and HTTP headers are great solutions, but both would require explicit server side involvement.

For simple sites, or where I don't have backend access, I prefer client side solutions.

--

I use the following to set a class attribute to the HTML element itself, so my CSS can handle pretty much all other display type logic.

METHODS:

1) place <script>document.getElementsByTagName('html')[0].classList.add('js-enabled');</script> above the <html> element.

WARNING!!!! This method, will override all <html> class attributes, not to mention may not be "valid" HTML, but works in all browsers, I've tested it in.

*NOTES: Due to the timing of when the script is run, before the <html> tag is processed, it ends up getting an empty classList collection with no nodes, so by the time the script completes, the <html> element will be given only the classes you added.

2) Preserves all other <html> class attributes, simply place the script <script>document.getElementsByTagName('html')[0].classList.add('js-enabled');</script> right after the opening <html> tag.

In both cases, If JS was disabled, then no changes to the <html> class attributes will be made.

ALTERNATIVES

Over the years I've used a few other methods:

    <script type="text/javascript">
    <!-- 
        (function(d, a, b){ 
            let x = function(){
                // Select and swap
                let hits = d.getElementsByClassName(a);
                for( let i = hits.length - 1; i >= 0; i-- ){
                    hits[i].classList.add(b);
                    hits[i].classList.remove(a);
                }
            };
            // Initialize Second Pass...
            setTimeout(function(){ x(); },0);
            x();
        })(document, 'no-js', 'js-enabled' );
    -->
</script>

// Minified as:

<script type="text/javascript">
    <!-- 
        (function(d, a, b, x, hits, i){x=function(){hits=d.getElementsByClassName(a);for(i=hits.length-1;i>=0;i--){hits[i].classList.add(b);hits[i].classList.remove(a);}};setTimeout(function(){ x(); },0);x();})(document, 'no-js', 'js-enabled' );
    -->
</script>
  • This will cycle through the page twice, once at the point where it is in the page, generally right after the <html> and once again after page load. Two times was required, as I injected into a header.tpl file of a CMS which I did not have backend access to, but wanted to present styling options for no-js snippets.

The first pass, would set set the .js-enabled class permitting any global styles to kick in, and prevented most further reflows. the second pass, was a catchall for any later included content.

REASONINGS:

The main reasons, I've cared if JS was enabled or not was for "Styling" purposes, hide/show a form, enable/disable buttons or restyle presentation and layouts of sliders, tables, and other presentations which required JS to function "correctly" and would be useless or unusable without JS to animate or handle the interactions.

Also, you can't directly detect with javascript, if javascript is "disabled"... only if it is "enabled", by executing some javascript, so you either rely on <meta http-equiv="refresh" content="2;url=/url/to/no-js/content.html" /> or you can rely on css to switch styles and if javascript executes, to switch to a "js-enabled" mode.

Avantgarde answered 23/9, 2008 at 14:7 Comment(0)
L
1

Here is the twist! There might be client browsers with enabled Javascript and who use JS compatible browsers. But for what ever the reason Javascript does not work in the browser (ex: firewall settings). According to statistics this happens every 1 out of 93 scenarios. So the server detects the client is capable of executing Javascript but actually it doesn't!

As a solution I suggest we set a cookie in client site then read it from server. If the cookie is set then JS works fine. Any thoughts ?

Levity answered 23/9, 2008 at 14:7 Comment(0)
F
1

Here is a PHP script which can be included once before any output is generated. It is not perfect, but it works well enough in most cases to avoid delivering content or code that will not be used by the client. The header comments explain how it works.

<?php
/*****************************************************************************
 * JAVASCRIPT DETECTION                                                      *
 *****************************************************************************/

// Progressive enhancement and graceful degradation are not sufficient if we
// want to avoid sending HTML or JavaScript code that won't be useful on the
// client side.  A normal HTTP request will not include any explicit indicator
// that JavaScript is enabled in the client.  So a "preflight response" is
// needed to prompt the client to provide an indicator in a follow-up request.
// Once the state of JavaScript availability has been received the state of
// data received in the original request must be restored before proceding.
// To the user, this handshake should be as invisible as possible.
// 
// The most convenient place to store the original data is in a PHP session.
// The PHP session extension will try to use a cookie to pass the session ID
// but if cookies are not enabled it will insert it into the query string.
// This violates our preference for invisibility.  When Javascript is not
// enabled the only way to effect a client side redirect is with a "meta"
// element with its "http-equiv" attribute set to "refresh".  In this case
// modifying the URL is the only way to pass the session ID back.
//
// But when cookies are disabled and JavaScript is enabled then a client side
// redirect can be effected by setting the "window.onload" method to a function
// which submits a form.  The form has a "method" attribute of "post" and an
// "action" attribute set to the original URL.  The form contains two hidden
// input elements, one in which the session ID is stored and one in which the
// state of JavaScript availability is stored.  Both values are thereby passed
// back to the server in a POST request while the URL remains unchanged.  The
// follow-up request will be a POST even if the original request was a GET, but
// since the original request data is restored, the containing script ought to
// process the request as though it were a GET.

// In order to ensure that the constant SID is defined as the caller of this
// script would expect, call session_start if it hasn't already been called.
$session = isset($_SESSION);
if (!$session) session_start();

// Use a separate session for Javascript detection.  Save the caller's session
// name and ID.  If this is the followup request then close the caller's
// session and reopen the Javascript detection session.  Otherwise, generate a
// new session ID, close the caller's session and create a new session for
// Javascript detection.
$session_name = session_name();
$session_id = session_id();
session_write_close();
session_name('JS_DETECT');
if (isset($_COOKIE['JS_DETECT'])) {
    session_id($_COOKIE['JS_DETECT']);
} elseif (isset($_REQUEST['JS_DETECT'])) {
    session_id($_REQUEST['JS_DETECT']);
} else {
    session_id(sha1(mt_rand()));
}
session_start();

if (isset($_SESSION['_SERVER'])) {
    // Preflight response already sent.
    // Store the JavaScript availability status in a constant.
    define('JS_ENABLED', 0+$_REQUEST['JS_ENABLED']);
    // Store the cookie availability status in a constant.
    define('COOKIES_ENABLED', isset($_COOKIE['JS_DETECT']));
    // Expire the cookies if they exist.
    setcookie('JS_DETECT', 0, time()-3600);
    setcookie('JS_ENABLED', 0, time()-3600);
    // Restore the original request data.
    $_GET = $_SESSION['_GET'];
    $_POST = $_SESSION['_POST'];
    $_FILES = $_SESSION['_FILES'];
    $_COOKIE = $_SESSION['_COOKIE'];
    $_SERVER = $_SESSION['_SERVER'];
    $_REQUEST = $_SESSION['_REQUEST'];
    // Ensure that uploaded files will be deleted if they are not moved or renamed.
    function unlink_uploaded_files () {
        foreach (array_keys($_FILES) as $k)
            if (file_exists($_FILES[$k]['tmp_name']))
                unlink($_FILES[$k]['tmp_name']);
    }
    register_shutdown_function('unlink_uploaded_files');
    // Reinitialize the superglobal.
    $_SESSION = array();
    // Destroy the Javascript detection session.
    session_destroy();
    // Reopen the caller's session.
    session_name($session_name);
    session_id($session_id);
    if ($session) session_start();
    unset($session, $session_name, $session_id, $tmp_name);
    // Complete the request.
} else {
    // Preflight response not sent so send it.
    // To cover the case where cookies are enabled but JavaScript is disabled,
    // initialize the cookie to indicate that JavaScript is disabled.
    setcookie('JS_ENABLED', 0);
    // Prepare the client side redirect used when JavaScript is disabled.
    $content = '0; url='.$_SERVER['REQUEST_URI'];
    if (!$_GET['JS_DETECT']) {
        $content .= empty($_SERVER['QUERY_STRING']) ? '?' : '&';
        $content .= 'JS_DETECT='.session_id();
    }
    // Remove request data which should only be used here.
    unset($_GET['JS_DETECT'],$_GET['JS_ENABLED'],
            $_POST['JS_DETECT'],$_POST['JS_ENABLED'],
            $_COOKIE['JS_DETECT'],$_COOKIE['JS_ENABLED'],
            $_REQUEST['JS_DETECT'],$_REQUEST['JS_ENABLED']);
    // Save all remaining request data in session data.
    $_SESSION['_GET'] = $_GET;
    $_SESSION['_POST'] = $_POST;
    $_SESSION['_FILES'] = $_FILES;
    $_SESSION['_COOKIE'] = $_COOKIE;
    $_SESSION['_SERVER'] = $_SERVER;
    $_SESSION['_REQUEST'] = $_REQUEST;
    // Rename any uploaded files so they won't be deleted by PHP.  When using
    // a clustered web server, upload_tmp_dir must point to shared storage.
    foreach (array_keys($_FILES) as $k) {
        $tmp_name = $_FILES[$k]['tmp_name'].'x';
        if (move_uploaded_file($_FILES[$k]['tmp_name'], $tmp_name))
            $_SESSION['_FILES'][$k]['tmp_name'] = $tmp_name;
    }
// Have the client inform the server as to the status of Javascript.
?>
<!DOCTYPE html>
<html>
<head>
    <script>
        document.cookie = 'JS_ENABLED=1';
// location.reload causes a confirm box in FireFox
//      if (document.cookie) { location.reload(true); }
        if (document.cookie) { location.href = location; }
    </script>
    <meta http-equiv="refresh" content="<?=$content?>" />
</head>
<body>
    <form id="formid" method="post" action="" >
        <input type="hidden" name="<?=$session_name?>" value="<?=$session_id?>" />
        <input type="hidden" name="JS_DETECT" value="<?=session_id()?>" />
        <input type="hidden" name="JS_ENABLED" value="1" />
    </form>
    <script>
        document.getElementById('formid').submit();
    </script>
</body>
</html>
<?php
    exit;
}
?>
Figwort answered 23/9, 2008 at 14:7 Comment(0)
S
0

CSS has now scripting media feature (supported by most major browsers):

<p id="yes">😀 You have scripting enabled</p>
<p id="no" >😞 You do not have scripting available</p>
#yes, #no { color: transparent; }

@media (scripting: enabled) {
  #yes {
    color: green;
  }
}

@media (scripting: none) {
  #no {
    color: red;
  }
}

#yes, #no { color: transparent; }

@media (scripting: enabled) {
  #yes {
    color: green;
  }
}

@media (scripting: none) {
  #no {
    color: red;
  }
}
<p id="yes">😀 You have scripting enabled</p>
<p id="no" >😞 You do not have scripting available</p>
Shaver answered 23/9, 2008 at 14:7 Comment(0)
W
0

I have one more exciting way to detect is JS is enabled or not, follow the steps to know whether Js is enabled or not on the server side:

server.js:

const {jsinfo} = require('visInfo.js'); 
const {visinfo} = require('visInfo.js'); 
app.get('/', async (req, res) => {
res.render('clientPage.html', async (err, html)=>{
visinfo();
res.send(html)
})    
}); 

app.post('/isJSpost', (req, res) => {
    await jsinfo(req);
    res.json({ success: true })
});  

visInfo.js:

let isJs //make it global variable [necessary]
async function jsinfo(req){
try{
isJs = req.body.isjs
}catch(err){
console.log( 'visinfo.js:jsinfo()::',err.message)
}
}
async function jsextract(){
json = {}
json['isJs'] = isJs
return json
}
async function destroy(){
isJs = undefined
}

async function visinfo() {
  await new Promise(resolve => setTimeout(resolve, 4000)); // [necessary]
  jsjson = await jsextract () ;
  console.log(jsjson)
  await destroy();
}
module.exports = { visinfo , jsinfo} ; 

Include this code in clientPage.html in the head section at the topmost position.

function run () {
    isJs = 1
    xhr = new XMLHttpRequest();
    xhr.open('POST', '/isJSpost');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({ 
      isjs: isJs 
    }));
}
run();

You can try the code and if JS is enabled you will see {isJs: 1} else it will be undefined, you can try this code by switching devices/browsers/clients or toggling the JS any number of times it won't fail.

Wangle answered 23/9, 2008 at 14:7 Comment(0)
P
0

I've had to solve the same problem yesterday, so I'm just adding my .001 here. The solution works for me ok at least at the home page (index.php)

I like to have only one file at the root folder: index.php . Then I use folders to structure the whole project (code, css, js, etc). So the code for index.php is as follows:

<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>

Hope this helps anyone. Best Regards.

Pluto answered 23/9, 2008 at 14:7 Comment(3)
not adviced; google cannot find you this way, also jou dont need jquery and you can execute During load because this page requires noting extraSinusoidal
Why load jQuery just to redirect the user?Tetroxide
window.onload = function(){ window.location = "code/home.php"; } or if you'd prefer an 80k library for a redirect, cool.Discrimination
D
-4

Might sound a strange solution, but you can give it a try :

<?php $jsEnabledVar = 0; ?>    

<script type="text/javascript">
var jsenabled = 1;
if(jsenabled == 1)
{
   <?php $jsEnabledVar = 1; ?>
}
</script>

<noscript>
var jsenabled = 0;
if(jsenabled == 0)
{
   <?php $jsEnabledVar = 0; ?>
}
</noscript>

Now use the value of '$jsEnabledVar' throughout the page. You may also use it to display a block indicating the user that JS is turned off.

hope this will help

Dispassionate answered 23/9, 2008 at 14:7 Comment(4)
Please make sure to initialize the $jsEnabledVar = 0;Dispassionate
I think you are confusing the order in which things happen. The php parser will execute the php code server-side while serving the page; the javascript is not executing. Only when the client gets the page, and all php code has already executed, will the javascript execute.Amygdaline
Dude, script will be served first from a server, so things will be parsed first server side! Your script is totally nonsense.Doig
You're trying to run a script inside <noscript> when it means that the user does NOT HAVE JAVASCRIPT ENABLED.Felicefelicia

© 2022 - 2024 — McMap. All rights reserved.