Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS #media attribute? I would like to run a different script if the browser is on a handheld device.
The jQuery $.browser function is not what I am looking for.
Editor's note: user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.
Instead of using jQuery you can use simple JavaScript to detect it:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
}
Or you can combine them both to make it more accessible through jQuery...
$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
Now $.browser will return "device" for all above devices
Note: $.browser removed on jQuery v1.9.1. But you can use this by using jQuery migration plugin Code
A more thorough version:
var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
isMobile = true;
}
For me small is beautiful so I'm using this technique:
In CSS file:
/* Smartphones ----------- */
#media only screen and (max-width: 760px) {
#some-element { display: none; }
}
In jQuery/JavaScript file:
$( document ).ready(function() {
var is_mobile = false;
if( $('#some-element').css('display')=='none') {
is_mobile = true;
}
// now I can use is_mobile to run javascript conditionally
if (is_mobile == true) {
//Conditional script here
}
});
My objective was to have my site "mobile-friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.
For example, in my mobile version I don't want to activate the Facebook Like Box, because it loads all those profile images and stuff. And that's not good for mobile visitors. So, besides hiding the container element, I also do this inside the jQuery code block (above):
if(!is_mobile) {
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
You can see it in action at http://lisboaautentica.com
I'm still working on the the mobile version, so it's still not looking as it should, as of writing this.
Update by dekin88
There is a JavaScript API built-in for detecting media.
Rather than using the above solution simply use the following:
$(function() {
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
if (isMobile) {
//Conditional script here
}
});
Browser Supports: http://caniuse.com/#feat=matchmedia
The advantage of this method is that it's not only simpler and shorter, but you can conditionally target different devices such as smartphones and tablets separately if necessary without having to add any dummy elements into the DOM.
According to Mozilla - Browser detection using the user agent:
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
Like this:
if (/Mobi/.test(navigator.userAgent)) {
// mobile!
}
This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.
Update for Android
EricL recommends testing for Android as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):
if (/Mobi|Android/i.test(navigator.userAgent)) {
// mobile!
}
A simple and effective one-liner:
function isMobile() { return ('ontouchstart' in document.documentElement); }
However above code doesn't take into account the case for laptops with touchscreen.
Thus, I provide this second version, based on #Julian solution:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
It's not jQuery, but I found this: http://detectmobilebrowser.com/
It provides scripts to detect mobile browsers in several languages, one of which is JavaScript. That may help you with what you're looking for.
However, since you are using jQuery, you might want to be aware of the jQuery.support collection. It's a collection of properties for detecting the capabilities of the current browser. Documentation is here: http://api.jquery.com/jQuery.support/
Since I don't know what exactly what you're trying to accomplish, I don't know which of these will be the most useful.
All that being said, I think your best bet is to either redirect or write a different script to the output using a server-side language (if that is an option). Since you don't really know the capabilities of a mobile browser x, doing the detection, and alteration logic on the server side would be the most reliable method. Of course, all of that is a moot point if you can't use a server side language :)
Sometimes it is desired to know which brand device a client is using in order to show content specific to that device, like a link to the iPhone store or the Android market. Modernizer is great, but only shows you browser capabilities, like HTML5, or Flash.
Here is my UserAgent solution in jQuery to display a different class for each device type:
/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
var ua = navigator.userAgent;
var checker = {
iphone: ua.match(/(iPhone|iPod|iPad)/),
blackberry: ua.match(/BlackBerry/),
android: ua.match(/Android/)
};
if (checker.android){
$('.android-only').show();
}
else if (checker.iphone){
$('.idevice-only').show();
}
else if (checker.blackberry){
$('.berry-only').show();
}
else {
$('.unknown-device').show();
}
}
This solution is from Graphics Maniacs
http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
Found a solution in: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
And then to verify if its a Mobile, you can test using:
if(isMobile.any()) {
//some code...
}
If by "mobile" you mean "small screen," I use this:
var windowWidth = window.screen.width < window.outerWidth ?
window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
On iPhone you'll end up with a window.screen.width of 320. On Android you'll end up with a window.outerWidth of 480 (though that can depend on the Android). iPads and Android tablets will return numbers like 768 so they'll get the full view like you'd want.
In one line of javascript:
var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));
If the user agent contains 'Mobi' (as per MDN) and ontouchstart is available then it is likely to be a mobile device.
EDIT: Updates the regex code in response to feedback in the comments. Using regex/mobi/i the i makes it case-insensitive, and mobi matches all mobile browsers. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox
I know this question has a lot of answers, but from what I saw nobody approaches the answer the way I would solve this.
CSS uses width (Media Queries) to determine which styles applied to the web document baseed on width. Why not use width in the JavaScript?
For instance in Bootstrap's (Mobile First) Media Queries, there exist 4 snap/break points:
Extra Small Devices are 768 pixels and under.
Small Devices range from 768 to 991 pixels.
Medium Devices range from 992 to 1199 pixels.
Large Devices are 1200 pixels and up.
We can use this to also solve our JavaScript issue as well.
First we will create a function that gets the window size and returns a value that allows us to see what size device is viewing our application:
var getBrowserWidth = function(){
if(window.innerWidth < 768){
// Extra Small Device
return "xs";
} else if(window.innerWidth < 991){
// Small Device
return "sm"
} else if(window.innerWidth < 1199){
// Medium Device
return "md"
} else {
// Large Device
return "lg"
}
};
Now that we have the function set up, we can call it ans store the value:
var device = getBrowserWidth();
Your question was
I would like to run a different script if the browser is on a handheld device.
Now that we have the device information all that is left is an if statement:
if(device === "xs"){
// Enter your script for handheld devices here
}
Here is an example on CodePen: http://codepen.io/jacob-king/pen/jWEeWG
You can't rely on navigator.userAgent, not every device reveals its real OS. On my HTC for example, it depends on the settings ("using mobile version" on/off).
On http://my.clockodo.com, we simply used screen.width to detect small devices. Unfortunately, in some Android versions there's a bug with screen.width. You can combine this way with the userAgent:
if(screen.width < 500 ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
}
If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.
However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.
Also see this SO question
I am surprised that no one pointed out a nice site: http://detectmobilebrowsers.com/ It has ready made code in different languages for mobile detection (including but not limited to):
Apache
ASP
C#
IIS
JavaScript
NGINX
PHP
Perl
Python
Rails
And if you need to detect the tablets as well, just check About section for additional RegEx parameter.
Android tablets, iPads, Kindle Fires and PlayBooks are not detected by
design. To add support for tablets, add |android|ipad|playbook|silk to
the first regex.
If you're not particularly worried about small displays you could use width/height detection. So that way if width is under a certain size, the mobile site is thrown up. It may not be the perfect way, but it will probably be the easiest to detect for multiple devices. You may need to put in a specific one for the iPhone 4 (large resolution).
If found that just checking navigator.userAgent isn't always reliable. Greater reliability can be achieved by also checking navigator.platform. A simple modification to a previous answer seems to work better:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
// some code...
}
To add an extra layer of control I use the HTML5 storage to detect if it is using mobile storage or desktop storage. If the browser does not support storage I have an array of mobile browser names and I compare the user agent with the browsers in the array.
It is pretty simple. Here is the function:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi'];
var ua=navigator.userAgent.toLowerCase();
for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;
// nothing found.. assume desktop
return false;
}
I advise you check out http://wurfl.io/
In a nutshell, if you import a tiny JavaScript file:
<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
You will be left with a JSON object that looks like:
{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}
(That's assuming you are using a Nexus 7, of course) and you will be able to do things like:
if(WURFL.is_mobile) {
//dostuff();
}
This is what you are looking for.
Disclaimer: I work for the company that offers this free service.
Great answer thanks. Small improvement to support Windows phone and Zune:
if (navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/) ||
navigator.userAgent.match(/Windows Phone/i) ||
navigator.userAgent.match(/ZuneWP7/i)
) {
// some code
self.location = "top.htm";
}
I know it's very old question about this kind of detection.
My solution is based on scroller width (is exist or not).
// this function will check the width of scroller
// if scroller width is 0px it's mobile device
//function ismob() {
var dv = document.getElementById('divscr');
var sp=document.getElementById('res');
if (dv.offsetWidth - dv.clientWidth == 10) {sp.innerHTML='Is mobile'; //return true;
} else {
sp.innerHTML='It is not mobile'; //return false;
}
//}
<!-- put hidden div on very begining of page -->
<div id="divscr" style="position:fixed;top:0;left:0;width:50px;height:50px;overflow:hidden;overflow-y:scroll;z-index:-1;visibility:hidden;"></div>
<span id="res"></span>
You can use media query to be able to handle it easily.
isMobile = function(){
var isMobile = window.matchMedia("only screen and (max-width: 760px)");
return isMobile.matches ? true : false
}
Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
Here's a function you can use to get a true/false answer as to whether you're running on a mobile browser. Yes, it is browser-sniffing, but sometimes that is exactly what you need.
function is_mobile() {
var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
for(i in agents) {
if(navigator.userAgent.match('/'+agents[i]+'/i')) {
return true;
}
}
return false;
}
Use this:
/** * jQuery.browser.mobile (http://detectmobilebrowser.com/) * jQuery.browser.mobile will be true if the browser is a mobile device **/ (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
Then use this:
if(jQuery.browser.mobile)
{
console.log('You are using a mobile device!');
}
else
{
console.log('You are not using a mobile device!');
}
All answers use user-agent to detect the browser but device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).
To detect mobile you can check for touch events:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}
Taken from What's the best way to detect a 'touch screen' device using JavaScript?
I would be suggesting to use following combo of strings, to check if device type being used.
As per Mozilla documentation string Mobi is recommended. But, some of the old tablets doesn't return true if only Mobi is used, hence we should use Tablet string too.
Similarly, for being on the safe side iPad and iPhone strings could also be used to check the device type.
Most of the new devices would return true for Mobi string alone.
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}
I know this old question and there is a lot of answer but I think this function is simple and will help for detect all mobile, Tablet and computer browser it work like a charm.
function Device_Type()
{
var Return_Device;
if(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|w3c|acs\-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd\-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg\-c|lg\-d|lg\-g|lge\-|maui|maxo|midp|mits|mmef|mobi|mot\-|moto|mwbp|nec\-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch\-|sec\-|send|seri|sgh\-|shar|sie\-|siem|smal|smar|sony|sph\-|symb|t\-mo|teli|tim\-|tosh|tsm\-|upg1|upsi|vk\-v|voda|wap\-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda\-) /i.test(navigator.userAgent))
{
if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent))
{
Return_Device = 'Tablet';
}
else
{
Return_Device = 'Mobile';
}
}
else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent))
{
Return_Device = 'Tablet';
}
else
{
Return_Device = 'Desktop';
}
return Return_Device;
}
Simple function based on http://detectmobilebrowser.com/
function isMobile() {
var a = navigator.userAgent||navigator.vendor||window.opera;
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4));
}
<script>
function checkIsMobile(){
if(navigator.userAgent.indexOf("Mobile") > 0){
return true;
}else{
return false;
}
}
</script>
If you goto any browser and if you try to get navigator.userAgent then we'll be getting the browser information something like following
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
The same thing if you do in mobile you'll be getting following
Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPP6.171019.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36
Every mobile browser will have useragent with string containing "Mobile" So I'm using above snippet in my code to check whether current user agent is web/mobile. Based on the result I'll be doing required changes.
I use this
if(navigator.userAgent.search("mobile")>0 ){
do something here
}
How about mobiledetect.net?
Other solutions seem too basic. This is a lightweight PHP class. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can also benefit from Mobile Detect by using any of the 3rd party plugins available for: WordPress, Drupal, Joomla, Magento, etc.
Related
I am developing site in php with responsive HTML. Now, I want to hide menu if user open that site in mobile browser (iOS and Android).
Then how i can verify in HTML or jQuery so i can hide menu. I tried to find but not get any proper solution.
Let me know if any one have.
Thanks
with CSS you can use #media-queries like the following:
#media screen and (max-width: 1199px) {
.your-navigation{
display:none;
}
}
or you use jQuery like the following:
if($(window).width()<=1199){
$(".your-navigation").hide();
}
but i would go with media queries, because its a more elegant and more easy to change way!
so actually you are not checking if its a mobile browser or desktop, but its totally okay, to check the width of the browser... i think, thats more what you want...
** edit **
after some thoughts i just wanna say, that it is possible to get the current browser by using javascript, but i wouldn't recommend that to you, because its not rubust and you will have a lot of pain with getting all browsers and so on... as i already said, go with the width! :)
(here is a link with an approach)
** edit 2 **
regarding your comment:
check this link out, it should be exactly what you want
here the code, thanks to feeela
/**
* Determine the mobile operating system.
* This function either returns 'iOS', 'Android' or 'unknown'
*
* #returns {String}
*/
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) )
{
return 'iOS';
}
else if( userAgent.match( /Android/i ) )
{
return 'Android';
}
else
{
return 'unknown';
}
}
I have a project that requires <a href="tel:123456"> over the phone number (123456 is not the number) however this will cause an issue for everything except mobile browsers by being unable to interpret the tel: bit.
I have tried to use jQuery to add the href attr when a browser width is <1000px but this is a very unreliable method (tablets also have a limited resolution).
Any ideas on how to overcome this would be greatly appreciated. I am using PHP, jQuery and JavaScript.
Detect with PHP if its a mobile agent:
http://www.000webhost.com/forum/scripts-code-snippets/27404-php-extremely-simple-way-check-if-mobile-browser.html
<?php
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo '<a href="tel:123456">';
}else{
echo 'You are not in a mobile';
}
?>
Since you're using PHP I can recommend the php-mobile-detect class. You can cater to individual devices/OS'es/browsers, or simply use isMobile() or isTablet() as a catch-all.
I usually do something like this:
include './includes/Mobile_Detect.php';
$detect = new Mobile_Detect;
if ( $detect->isMobile() or $detect->isTablet() ){
$phone='1-234-567-8910';
} else {
$phone='1-234-567-8910';
}
Then I just <?php echo $phone;?> wherever I need it and it works a treat! And by using PHP instead of javascript it means the detection is done server-side, so the end user has less to download (like jQuery and extra scripts).
The library of devices gets updated fairly often, so it's worth checking the GitHub page every so often.
Try this below one :
Syntex : callto
9566603286
<?php
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo '9566603286';
}else{
echo 'You are not in a mobile';
}
?>
A lot of you are probably aware of the new EU privacy law, but for those who are not, it basically means no site operated by a company resident in the EU can set cookies classed as 'non-essential to the operation of the website' on a visitors machine unless given express permission to do so.
So, the question becomes how to best deal with this?
Browsers obviously have the ability to block cookies from a specific website built in to them. My question is, is there a way of doing something similar using JS or PHP?
i.e. intercept any cookies that might be trying to be set (including 3rd party cookies like Analytics, or Facebook), and block them unless the user has given consent.
It's obviously possible to delete all cookies once they have been set, but although this amounts to the same thing as not allowing them to be set in the first place, I'm guessing that it's not good enough in this case because it doesn't adhere to the letter of the law.
Ideas?
I'm pretty interested in this answer too. I've accomplished what I need to accomplish in PHP, but the JavaScript component still eludes me.
Here's how I'm doing it in PHP:
$dirty = false;
foreach(headers_list() as $header) {
if($dirty) continue; // I already know it needs to be cleaned
if(preg_match('/Set-Cookie/',$header)) $dirty = true;
}
if($dirty) {
$phpversion = explode('.',phpversion());
if($phpversion[1] >= 3) {
header_remove('Set-Cookie'); // php 5.3
} else {
header('Set-Cookie:'); // php 5.2
}
}
Then I have some additional code that turns this off when the user accepts cookies.
The problem is that there are third party plugins being used in my site that manipulate cookies via javascript and short of scanning through them to determine which ones access document.cookie - they can still set cookies.
It would be convenient if they all used the same framework, so I might be able to override a setCookie function - but they don't.
It would be nice if I could just delete or disable document.cookie so it becomes inaccessible...
EDIT:
It is possible to prevent javascript access to get or set cookies.
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
EDIT 2:
For this to work in IE:
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return ''},
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );
}
I adapted Michaels codes from here to come up with this.
Basically it uses the defineGetter and defineSetter methods to set all the cookies on the page and then remove the user specified ones, this role could of course also be reversed if this is what you are aiming for.
I have tested this with third party cookies such as Google Analytics and it appears to work well (excluding the __utmb cookie means I am no longer picked up in Google Analytics), maybe you could use this and adapt it to your specific needs.
I've included the part about if a cookies name is not __utmb for your reference, although you could easily take these values from an array and loop through these that way.
Basically this function will include all cookies except those specified in the part that states if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
You could add to this using OR or AND filters or pull from an array, database, user input or whatever you like to exclude specific ones (useful for determining between essential and non-essential cookies).
function deleteSpecificCookies() {
var cookies = document.cookie.split(";");
var all_cookies = '';
for (var i = 0; i < cookies.length; i++) {
var cookie_name = cookies[i].split("=")[0];
var cookie_value = cookies[i].split("=")[1];
if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }
}
if(!document.__defineGetter__) {
Object.defineProperty(document, 'cookie', {
get: function(){return all_cookies; },
set: function(){return true},
});
} else {
document.__defineGetter__("cookie", function() { return all_cookies; } );
document.__defineSetter__("cookie", function() { return true; } );
}
}
You can not disable it completely but you can override the default setting with .htaccess
Try
SetEnv session.use_cookies='0';
If it is optional for some users don't use .htaccess
if(!$isAuth)
{
ini_set('session.use_cookies', '0');
}
A little bit old but I think you deserve a answer that works:
Step 1: Don't execute the third party script code.
Step 2: Show the cookie banner.
Step 3: Wait until user accepts, now you can execute the third party script code..
Worked for me.
How about not paying attention to hoaxes?
Aside from the fact that this is old news, the text clearly says that it only applies to cookies that are not essential to the site's function. Meaning session cookies, a shopping basket, or anything that is directly related to making the site work is perfectly fine. Anything else (tracking, stats, etc.) are "not allowed" without permission.
I have a website build using PHP and HTML. If a user browses my website using IE, I want to display a message saying: "Please use Firefox or Google Chrome" instead of rendering the index page.
Is it possible? If so how could it be done?
Please note I am not that advanced with PHP.
Thanks.
You could also do it like this:
<?php
function using_ie(){
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$ub =false;
if(preg_match('/MSIE/i',$user_agent))
{$ub = true;}
return $ub;
}
if(using_ie()==true){
//Show notice
}else{
//Cont
}
?>
Dont forget that that IE users still own 30% of the market share meaning 1 in 3.3 of your users will be using IE http://www.w3counter.com/globalstats.php
I will give you the best answer
include this code in <head>
<!--[if IE]>
<script>
alert("Here you can write the warning box like this website is not supported by IE");
</script>
<script type="text/javascript">
window.location = "insert here the link of the webpage you want to redirect the users after clicking ok";
</script>
<![endif]-->
You can do that with Conditional Comments which are documented by the browser vendor (Microsoft).
With those you can make HTML accessible to IE users that are hidden in comments in every other standards compliant browser, like the message to download some other browser. You can even completely hide the rest of the page.
It is possible, but i just want to tell you it's really not a really good solution to a problem. The way it can be done is:
$browserinfo = get_browser();
$browser = $browserinfo['browser']
if ($browser == "Internet Explorer" || $browser == "InternetExplorer" || $browser == "IE") {
include("path/to/your/errorMessage.php");
exit(0);
}
This does require browscap. Another option is:
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$ub = false;
if(preg_match('/MSIE/i',$u_agent))
{
include("path/to/your/errorMessage.php");
exit(0);
}
Please checkout the user-agent as described here
http://icfun.blogspot.de/2008/07/php-how-to-check-useragent.html
i hope this is what your are looking for ;-)
I'm trying to deploy flash files embeded in html to the google app engine.
Flash(action script 2.0) uses "post" method to send hostname and get its ip address through php function gethostbyname().
In fact, I know google app engine does not support php.
So I tried to use another way to deploy ipPHP.php in other free web server and only flash file in google app engine.
But it does not work and I can not know why.
Can you give me a tip for this problem ?
--------------domaintoip.fla ---------------------
result_lv = new LoadVars();
result_lv.byname = _root.domainnm;
trace("Sending... " + result_lv.byname);
result_lv.onLoad = function (success)
{
if (success)
{
_root.ip = unescape(this.result);
trace("Return value from the PHP : " + unescape(this));
if(_root.ip.length==5){
_root.flag=1;
}
else{
var mystring=_root.ip;
arr=mystring.split(".");
_root.ipby1=arr[0];
_root.ipby2=arr[1];
_root.ipby3=arr[2];
if(arr[3].length==15)
{
_root.ipby4=arr[3].substr(0,3);
}
if(arr[3].length==14)
{
_root.ipby4=arr[3].substr(0,2);
}
if(arr[3].length==13)
{
_root.ipby4=arr[3].substr(0,1);
}
_root.flag=0;
}
}
else
{
trace("Cannot call the PHP file...");
_root.flag=1;
}
}
result_lv.sendAndLoad("http://anotherserver../ipPHP.php", result_lv, "POST");
-------------- ipPHP.php ---------------------
<?php
$Var1 = $_POST['byname'];
$rtnValue = gethostbyname(trim($Var1));
if(ip2long($rtnValue) == -1 || $rtnValue == $Var1 ) {
$rtnValue =0;
echo (result=$rtnValue");
}
else {
echo("result=$rtnValue");
}
?>
If your site is hosted on the app engine, you cannot make AJAX calls to a host other than the app engine due to the Same Origin Policy. This limitation is generally true, and is not specific to the app engine. To generalize, for any web page hosted at domain X, that web page cannot make AJAX requests to domain Y.
You actually are experiencing a much more fundamental problem: When the only tool you have is a hammer, every problem looks like a nail. In fact, you can trivially handle POST requests with the app engine using the doPost method, and you can very easily get the client's IP address in a very similar manner as your PHP script. There is absolutely no reason to use PHP here; you've set up a completely new server to call one built-in PHP function? That's insane; you can do the exact same thing with an app engine servlet.
Consider the following code:
public void doPost(HttpServletRequest request,HttpServletResponse response) {
/* get "byname" param, equivalent to $POST['byname'] */
String rtnValue = request.getParameter("byname");
/* TODO: your if statements and other logic */
/* print response to client, equivalent to your echo statement */
response.getWriter().print("result=" + rtnValue);
}