JavaScript가 비활성화되어 있는지 감지하는 방법은 무엇입니까?
오늘 아침 얼마나 많은 사람들이 JavaScript를 비활성화하는지 묻는 게시물이있었습니다. 그런 다음 사용자가 비활성화했는지 확인하기 위해 어떤 기술을 사용할 수 있는지 궁금해하기 시작했습니다.
누구든지 JavaScript가 비활성화되었는지 감지하는 짧고 간단한 방법을 알고 있습니까? 내 의도는 브라우저가 JS를 활성화하지 않으면 사이트가 제대로 작동하지 않는다는 경고를 보내는 것입니다.
결국 JS가 없어도 작동 할 수있는 콘텐츠로 리디렉션하고 싶지만 시작하려면 자리 표시 자로이 탐지가 필요합니다.
JavaScript 강화 콘텐츠를 제공할지 여부를 결정하려고한다고 가정합니다. 최상의 구현은 완전히 저하되어 사이트가 JavaScript 없이도 계속 작동합니다. 또한 설명 할 수없는 이유로 요소를 사용하는 대신 서버 측 감지 를 의미한다고 가정합니다 <noscript>
.
서버 측 JavaScript 감지를 수행하는 좋은 방법이 없습니다. 대안으로 JavaScript를 사용하여 쿠키 를 설정 한 다음 후속 페이지보기에서 서버 측 스크립팅을 사용하여 해당 쿠키를 테스트 할 수 있습니다. 그러나 이는 쿠키가없는 방문자를 신규 방문자 또는 쿠키를 차단하는 방문자와 구별 할 수 없기 때문에 전달할 콘텐츠를 결정하는 데 적합하지 않습니다.
여기에 .02를 추가하고 싶습니다. 100 % 방탄은 아니지만 충분하다고 생각합니다.
저에게 문제는 "이 사이트는 자바 스크립트 없이는 잘 작동하지 않습니다."라는 메시지를 올리는 선호하는 예입니다. 그런 다음 사이트가 자바 스크립트없이 제대로 작동하는지 확인해야한다는 것입니다. 그리고 일단 그 길을 시작하면 JS가 꺼진 상태에서 사이트가 방탄이되어야한다는 사실을 깨닫기 시작합니다. 이것은 엄청난 추가 작업입니다.
그래서, 당신이 정말로 원하는 것은 "JS를 켜라, 바보"라는 페이지로의 "리디렉션"이다. 그러나 물론 메타 리디렉션을 안정적으로 수행 할 수는 없습니다. 그래서 여기에 제안이 있습니다.
<noscript>
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div class="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</noscript>
... 사이트의 모든 콘텐츠가 "pagecontainer"클래스의 div로 래핑됩니다. 그러면 noscript 태그 내의 CSS가 모든 페이지 콘텐츠를 숨기고 대신 표시하려는 "no JS"메시지를 표시합니다. 이것이 실제로 Gmail이하는 것처럼 보입니다. Google에 충분하다면 내 작은 사이트에도 충분합니다.
noscript
블록은 JavaScript가 비활성화 될 때 실행되며 일반적으로 JavaScript에서 생성 한 대체 콘텐츠를 표시하는 데 사용됩니다.
<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>
js가없는 사용자는 next_page
링크 를 받게 됩니다. 여기에 매개 변수를 추가하여 JS / 비 JS 링크를 통해 왔는지 아니면 JS를 통해 쿠키를 설정하려고 시도했는지를 다음 페이지에서 알 수 있습니다. 비활성화됩니다. 이 두 가지 예는 매우 사소하고 조작 할 수 있지만 아이디어를 얻습니다.
얼마나 많은 사용자가 자바 스크립트를 비활성화했는지에 대한 순전히 통계적인 아이디어를 원한다면 다음과 같이 할 수 있습니다.
<noscript>
<img src="no_js.gif" alt="Javascript not enabled" />
</noscript>
그런 다음 액세스 로그를 확인하여이 이미지가 히트 한 횟수를 확인하십시오. 약간 조잡한 솔루션이지만 사용자 기반에 대해 백분율 측면에서 좋은 아이디어를 제공합니다.
위의 접근 방식 (이미지 추적)은 텍스트 전용 브라우저 또는 js를 전혀 지원하지 않는 브라우저에서는 잘 작동하지 않으므로 사용자 기반이 주로 해당 영역으로 이동한다면 이것이 최선의 접근 방식이 아닐 수 있습니다.
이것이 나를 위해 일한 것입니다 : 자바 스크립트가 비활성화되면 방문자를 리디렉션합니다.
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
사용 사례가 양식 (예 : 로그인 양식)이 있고 서버 측 스크립트에서 사용자가 JavaScript를 활성화했는지 알아야하는 경우 다음과 같이 할 수 있습니다.
<form onsubmit="this.js_enabled.value=1;return true;">
<input type="hidden" name="js_enabled" value="0">
<input type="submit" value="go">
</form>
양식을 제출하기 전에 js_enabled 값이 1로 변경됩니다. 서버 측 스크립트가 0이면 JS가 없습니다. 1이 나오면 JS!
눈에 거슬리지 않는 JavaScript를 작성하여 다른 방법으로 이동하는 것이 좋습니다.
자바 스크립트가 비활성화 된 사용자를 위해 프로젝트의 기능이 작동하도록하고, 완료되면 자바 스크립트 UI 향상을 구현합니다.
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
본문에 .no-js 클래스를 사용하고 .no-js 상위 클래스를 기반으로 비 자바 스크립트 스타일을 만듭니다. 자바 스크립트가 비활성화 된 경우 모든 비 자바 스크립트 스타일을 얻을 수 있으며, JS 지원이있는 경우 .no-js 클래스가 대체되어 평소와 같이 모든 스타일을 제공합니다.
document.body.className = document.body.className.replace("no-js","js");
modernizr을 통해 HTML5 상용구 http://html5boilerplate.com/ 에서 사용되는 트릭 이지만 한 줄의 자바 스크립트를 사용하여 클래스를 대체 할 수 있습니다.
noscript 태그는 괜찮지 만 CSS로 할 수있는 HTML에 추가 내용이있는 이유
<noscript>
필요 하지도 않으며 XHTML에서 지원 되지 않는다는 것은 말할 것도 없습니다 .
작업 예 :
<!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>
이 예에서 JavaScript가 활성화 된 경우 사이트가 표시됩니다. 그렇지 않은 경우 "JavaScript를 활성화하십시오"메시지가 표시됩니다. JavaScript가 활성화되었는지 테스트하는 가장 좋은 방법은 JavaScript를 사용해 보는 것입니다! 작동하면 활성화되고 그렇지 않으면 활성화되지 않습니다.
간단한 JS 스 니펫을 사용하여 숨겨진 필드의 값을 설정할 수 있습니다. 다시 게시하면 JS가 활성화되었는지 여부를 알 수 있습니다.
또는 빠르게 닫는 팝업 창을 열어 볼 수 있습니다 (하지만 표시 될 수 있음).
또한 JS가 비활성화 된 브라우저에 텍스트를 표시하는 데 사용할 수있는 NOSCRIPT 태그가 있습니다.
noscript 태그를 살펴보고 싶을 것입니다.
<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>
조금 힘들지만 (hairbo가 나에게 아이디어를 주었다)
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>
어떤 경우에도 작동할까요? noscript 태그가 지원되지 않더라도 (일부 CSS 만 필요함) 비 CSS 솔루션을 아는 사람이 있습니까?
noscript 태그는 잘 작동하지만 기본적으로 noscript는 클라이언트 측 검사이므로 쓸모없는 JS 파일을 계속 제공하려면 각 추가 페이지 요청이 필요합니다.
JS로 쿠키를 설정할 수 있지만 다른 사람이 지적했듯이 실패 할 수 있습니다. 이상적으로는 JS 클라이언트 측을 감지하고 쿠키를 사용하지 않고 해당 사용자에 대해 JS가 활성화되었음을 나타내는 세션 서버 측을 설정하고 싶습니다.
가능성은 src 속성이 실제로 서버 측 스크립트 인 JavaScript를 사용하여 1x1 이미지를 동적으로 추가하는 것입니다. 이 스크립트는 JS가 활성화 된 현재 사용자 세션 ($ _SESSION [ 'js_enabled'])에 저장합니다. 그런 다음 1x1 빈 이미지를 브라우저에 다시 출력 할 수 있습니다. 이 스크립트는 JS를 비활성화 한 사용자에게는 실행되지 않으므로 $ _SESSION [ 'js_enabled']가 설정되지 않습니다. 그런 다음이 사용자에게 제공되는 추가 페이지에 대해 모든 외부 JS 파일을 포함할지 여부를 결정할 수 있지만 일부 사용자는 NoScript Firefox 추가 기능을 사용하거나 JS를 사용할 수 있으므로 항상 검사를 포함하고 싶을 것입니다. 다른 이유로 일시적으로 비활성화되었습니다.
추가 HTTP 요청으로 인해 페이지 렌더링 속도가 느려지지 않도록 페이지 끝에 가까운 곳에이 검사를 포함하는 것이 좋습니다.
이것을 각 페이지의 HEAD 태그에 추가하십시오.
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
그래서 당신은 :
<head>
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
</head>
Jay 덕분에.
나는 항상 브라우저에 볼만한 가치가있는 무언가를주고 싶기 때문에 종종이 트릭을 사용합니다.
첫째, 올바르게 실행하기 위해 JavaScript가 필요한 페이지 부분 (getElementById 호출 등을 통해 수정되는 수동 HTML 요소 포함)은 JavaScript를 사용할 수 없다는 가정하에있는 그대로 사용할 수 있도록 설계되었습니다. (거기에없는 것처럼 설계됨)
JavaScript가 필요한 모든 요소는 다음과 같은 태그 안에 넣습니다.
<span name="jsOnly" style="display: none;"></span>
그런 다음 문서 시작 부분에서 .onload
또는 document.ready
루프 내 에서 JS 종속 요소를 다시 켜 getElementsByName('jsOnly')
도록 설정합니다 .style.display = "";
. 이렇게하면 비 JS 브라우저는 사이트의 JS 종속 부분을 볼 필요가 없으며, 있으면 사이트가 준비되면 즉시 나타납니다.
이 방법에 익숙해지면 코드를 혼성화하여 두 상황을 모두 처리하는 것이 매우 쉽습니다. 비록 지금은 noscript
태그를 실험하고 있으며 몇 가지 추가 이점이있을 것으로 기대하지만.
일반적인 해결책은 noscript와 함께 메타 태그를 사용하여 페이지를 새로 고치고 JavaScript가 비활성화 된 경우 서버에 알립니다.
<!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.
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>
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.
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
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!
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.
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).
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.
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...
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 ;).
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.
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
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.
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()) . "'");
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.
Adding a refresh in meta inside noscript is not a good idea.
Because noscript tag is not XHTML compliant
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.
참고 URL : https://stackoverflow.com/questions/121203/how-to-detect-if-javascript-is-disabled
'program tip' 카테고리의 다른 글
일반 영어로 "git reset"은 무엇을합니까? (0) | 2020.10.02 |
---|---|
Bash 스크립트에 전달 된 인수 수 확인 (0) | 2020.10.02 |
콜백 함수 란 무엇입니까? (0) | 2020.10.02 |
모든 출력을 파일로 리디렉션 (0) | 2020.09.30 |
Android 스튜디오의 "기호 R을 확인할 수 없음" (0) | 2020.09.30 |