Just for the recommendation, if you manage to detect this at the end-visitor (if their Web browser has JS enabled or not), over a proxied hostname, you could achieve this with a Cloudflare Worker, or some other way, however the best practice would be to notice those kind of type of users with either “pop-up”, since they’d experience a broken Website whil visiting.
Example, you could return a simple notice while also feedback into the console if the visitor has JS enabled. Keep in mind, if you run this on each request, might cost you since Workers are billable. See the reference about pricing and more from the below article.
Worker code:
export default {
async fetch(request) {
// Fetch the original response from your website
const response = await fetch(request);
const contentType = response.headers.get("Content-Type") || "";
// Ensure we are working with HTML content
if (!contentType.includes("text/html")) {
return response;
}
// Modify the HTML response to include JavaScript detection, a pop-up, and console feedback
let htmlContent = await response.text();
const jsCheckScript = `
<style>
#no-js-popup {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
color: white;
font-size: 1.2em;
text-align: center;
z-index: 1000;
padding: 20px;
box-sizing: border-box;
}
#no-js-popup p {
margin-top: 20%;
}
</style>
<div id="no-js-popup">
<p>JavaScript is disabled in your browser. Please enable it for the best experience.</p>
</div>
<script>
// Hide the pop-up if JavaScript is enabled
document.getElementById('no-js-popup').style.display = 'none';
// Feedback in the console
console.log('JavaScript is enabled in your browser. Enjoy your experience!');
</script>
<noscript>
<style>
#no-js-popup {
display: block;
}
</style>
</noscript>
`;
// Inject the JavaScript detection code before the closing </body> tag
htmlContent = htmlContent.replace("</body>", `${jsCheckScript}</body>`);
// Return the modified response
return new Response(htmlContent, {
headers: response.headers,
});
},
};
End result when I have JS disabled in my Web browser and I cannot do anything on the Website until I enable JS again, otherwise I don’t see it:
How to create a Worker in Dashboard and bound it to your zone or URI path:
To block those people, you could also do it with a Worker and return some custom error page or the 403 error code.
May I ask why would you block visitors who don’t have JS enabled in their Web browser?