How can I prevent a page from loading if there is no javascript, but using php instead of <noscript>?

一个人想着一个人 提交于 2019-12-24 16:03:36

问题


I have a page with php and other stuff in the code. What I need to do is a way to check with php if there is javascript enabled in the browser. This way, the whole page source will be prevented to be loaded, instead of using that only prevents the page from loading, but allows the source code.


回答1:


PHP is a server-side language. There is no way to do this with PHP since it is run on the server, and then the result is sent to the client. The server has no knowledge of whether the client has JavaScript enabled or not.

If you don't want to show the code in your .html file when JS is disabled, then you don't have to use PHP. You could put the essential stuff in the .html file and load the rest in with JavaScript. If JavaScript is disabled, the rest of the stuff never gets loaded in the first place. (This is called progressive enhancement.)




回答2:


This example will use the <noscript></noscript> tag inside an echo directive.

<?php

echo "<noscript>You need JS enabled to view the text on this page.</noscript>";

?>

<!DOCTYPE html>

<html>
<head>

</head>

<body>

<script>
document.write("<h1>Heading Text</h1>");
document.write("<p>This message appeared because you have JS enabled.</p>");
</script>



</body>

</html>



回答3:


You could make JavaScript fire a request to a page, setting a session variable enabling access to the website, then reload the page. This is by no means secure.

In all files except enable.php (could be done via an include/etc) before anything is echoed.

...
if (!isset($_SESSION['enabled']) { ?>
<!doctype html>
<html>
    <head>
        ...
        <script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/enable.php', false);
xhr.send();
window.location.reload();
        </script>
    </head>
    <body></body>
</html>
<?php die();
}
....

In enable.php, you would then do

$_SESSION['enabled'] = 1;

enable.php would only need to be hit once-per-session and if JavaScript was disabled afterwards, or it was hit manually by pointing the browser there, your server will not know the difference. The assumption is the client must have JavaScript enabled for this session if the page was reached this session.



来源:https://stackoverflow.com/questions/18549058/how-can-i-prevent-a-page-from-loading-if-there-is-no-javascript-but-using-php-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!