Auto detect mobile browser (via user-agent?) [closed] - html

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
How can I detect if a user is viewing my web site from a mobile web browser so that I can then auto detect and display the appropriate version of my web site?

There are open source scripts on Detect Mobile Browser that do this in Apache, ASP, ColdFusion, JavaScript and PHP.

Yes, reading the User-Agent header will do the trick.
There are some lists out there of known mobile user agents so you don't need to start from scratch. What I did when I had to is to build a database of known user agents and store unknowns as they are detected for revision and then manually figure out what they are. This last thing might be overkill in some cases.
If you want to do it at Apache level, you can create a script which periodically generates a set of rewrite rules checking the user agent (or just once and forget about new user agents, or once a month, whatever suits your case), like
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/$1
which would move, for example, requests to http://domain/index.html to http://domain/mobile/index.html
If you don't like the approach of having a script recreate a htaccess file periodically, you can write a module which checks the User Agent (I didn't find one already made, but found this particularly appropriate example) and get the user agents from some sites to update them. Then you can complicate the approach as much as you want, but I think in your case the previous approach would be fine.

Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.

Here's how I do it in JavaScript:
function isMobile() {
var index = navigator.appVersion.indexOf("Mobile");
return (index > -1);
}
See an example at www.tablemaker.net/test/mobile.html where it triples the font size on mobile phones.

My favorite Mobile Browser Detection mechanism is WURFL. It's updated frequently and it works with every major programming/language platform.

Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.
#media screen and (max-width:1025px) {
#content {
width: 100%;
}
}
You can set the width to whatever you want, but 1025 will catch the iPad landscape view.
You'll also want to add the following meta tag to your head:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
Check out this article over at HTML5 Rocks for some good examples

for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM
<script language="javascript"> <!--
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
alert("MOBILE DEVICE DETECTED");
document.write("<b>------------------------------------------<br>")
document.write("<b>" + navigator.userAgent + "<br>")
document.write("<b>------------------------------------------<br>")
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
document.write("<b> ANDROID MOBILE <br>")
else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
document.write("<b> ANDROID TABLET <br>")
else if ((userAgent.search("blackberry") > -1))
document.write("<b> BLACKBERRY DEVICE <br>")
else if ((userAgent.search("iphone") > -1))
document.write("<b> IPHONE DEVICE <br>")
else if ((userAgent.search("ipod") > -1))
document.write("<b> IPOD DEVICE <br>")
else if ((userAgent.search("ipad") > -1))
document.write("<b> IPAD DEVICE <br>")
else
document.write("<b> UNKNOWN DEVICE <br>")
}
else
alert("NO MOBILE DEVICE DETECTED"); //--> </script>

The Mobile Device Browser File is a great way to detect mobile (and other) broswers for ASP.NET projects: http://mdbf.codeplex.com/

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice == true)
{
Response.Redirect("Mobile//home.aspx");
}
}
This example works in asp.net

You can detect mobile clients simply through navigator.userAgent , and load alternate scripts based on the detected client type as:
$(document).ready(function(e) {
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/i)
|| navigator.userAgent.match(/Windows Phone/i)) {
//write code for your mobile clients here.
var jsScript = document.createElement("script");
jsScript.setAttribute("type", "text/javascript");
jsScript.setAttribute("src", "js/alternate_js_file.js");
document.getElementsByTagName("head")[0].appendChild(jsScript );
var cssScript = document.createElement("link");
cssScript.setAttribute("rel", "stylesheet");
cssScript.setAttribute("type", "text/css");
cssScript.setAttribute("href", "css/alternate_css_file.css");
document.getElementsByTagName("head")[0].appendChild(cssScript);
}
else{
// write code for your desktop clients here
}
});

You can check the User-Agent string. In JavaScript, that's really easy, it's just a property of the navigator object.
var useragent = navigator.userAgent;
You can check if the device if iPhone or Blackberry in JS with something like
var isIphone = !!agent.match(/iPhone/i),
isBlackberry = !!agent.match(/blackberry/i);
if isIphone is true you are accessing the site from an Iphone, if isBlackBerry you are accessing the site from a Blackberry.
You can use "UserAgent Switcher" plugin for firefox to test that.
If you are also interested, it may be worth it checking out my script "redirection_mobile.js" hosted on github here https://github.com/sebarmeli/JS-Redirection-Mobile-Site and you can read more details in one of my article here:
http://blog.sebarmeli.com/2010/11/02/how-to-redirect-your-site-to-a-mobile-version-through-javascript/

You haven't said what language you're using. If it's Perl then it's trivial:
use CGI::Info;
my $info = CGI::Info->new();
if($info->is_mobile()) {
# Add mobile stuff
}
unless($info->is_mobile()) {
# Don't do some things on a mobile
}

Yes user-agent is used to detect mobile browsers. There are lots of free scripts available to check this. Here is one such php code which will help you redirect mobile users to different website.

I put this demo with scripts and examples included together:
http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/
This example utilizes php functions for user agent detection and offers the additional benefit of permitting users to state a preference for a version of the site which would not typically be the default based on their browser or device type. This is done with cookies (maintained using php on the server-side as opposed to javascript.)
Be sure to check out the download link in the article for the examples.
Hope you enjoy!

MobileESP has PHP, Java, APS.NET (C#), Ruby and JavaScript hooks.
it has also the Apache 2 licence, so free for commercial use.
Key thing for me is it only identifies browsers and platforms not screen sizes and other metrics, which keeps it nice an small.

There's a brand new solution using Zend Framework. Start from the link to Zend_HTTP_UserAgent:
http://framework.zend.com/manual/en/zend.http.html

Related

Clickable tel protocol a tag in firefox

I have a pretty standard a tag for a telephone number. It works in everything except Firefox. I thought the tel protocol was standard - is there a workaround I am unaware of?
<a class="tel" href="tel:8001234567">(800) 123-4567</a>
Firefox error message:
The address wasn't understood
Firefox doesn't know how to open this address, because the protocol (tel) isn't associated with any program.
You might need to install other software to open this address.
Firefox doesn't know a program for every protocol. The user would need to specify a program in the settings in this case. There is no server-side workaround for this, except replacing it with the unofficial callto: introduced by Skype.
I know this is an old question, but this might help if you need a workaround:
var isFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
var isMobile = (typeof window.orientation !== "undefined") ||
(navigator.userAgent.indexOf('IEMobile') !== -1);
if(isFirefox && !isMobile) {
$('a[href^="tel:"]').click(function() { return false; });
}
NOTE:
As #Peter pointed out, this code definitely disables tel: links on Firefox. I added a detection for mobile device (found here) to limit side effects, but it still disables third-party applications that could handle it on desktop.
The phone link DOES work in firefox, and, if no phone app is installed, it informs you why it cannot call the number. It is not an error message, and as comments point out the "solutions" are not appropriate. I am using this hint for pc users in my responsive web site:
<a class="tel" href="tel:8001234567"
title="Clicking this link only works on a mobile phone">
(800) 123-4567
</a>
While not the exact truth, it will explain to most pc users, who do not have a telephone application installed, that they should not utilize the phone number as a clickable link, while mobile users, who have no mouse, will never see the tooltip. Desktop users with a phone app will probably be used to click phone links, and also understand that the tooltip is meant for desktop users without phone app.
I did not uninstall my mail to test if the same message is shown on an anchor tag with href="mailto:...". The message is kind of general to handle any protocol that is not installed, so it sounds kind of cryptic to some users.
I hope my footnote is not outdated.
Current version of firefox copes pretty fine with the href="tel: (on Windows 10, which asks me to define the required application for the telephone call).
But:
It seems firefox has still problems with AJAX-calls following the onclick-event on the tel-link.
HTML:
anynumber
Javascript (experimental):
function log_action(aid,action2){
$.getJSON('myscript_ajax.php',
{action: "log_action",
actionid: aid,
action2: action2
})
.done(function(data)
{
console.log(data);
})
.error(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
});
}
While chrome logs the response from the php-script as expected, firefox displays the error-notice with empty text-status and response text.
Maybe the AJAX-request works fine in case a telephone IS installed, but i have none, and developing server-applications, I cannot know whether the client has, either.

redirect a mobile site only once

Hy i just want to know the code to paste to the "index.html" of my website so i Can ask Mobiles users if they want to be redirected to mobile version or go to desktop version
but i haven't figured out a way
Cause the code i found always redirect with no chance to go to desktop version on mobile
I am not able to post the code that i found but the question says it all
If this is not possible i just want to know a code that redirect mobile users only "ONCE" please and thank you
i have no professional experience in this...just a beginner
Following the instructions at http://www.ezmobilewebsitetools.com/howto-redirect.html:
Paste the following code in the <head> section of your index.html
<script>
if ((document.location.hostname.match(/\.mobi$/) || screen.width < 699)
&& (document.cookie.indexOf("skipmobile") == -1 || getCookie("skipmobile") == -1)
{
document.location = "mobile/"; //change this to location of your mobile site
} else if (document.location.search.indexOf("skipmobile") >= 0) {
document.cookie = "skipmobile=1";
}
//getCookie function from http://www.w3schools.com/js/js_cookies.asp
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) {
return unescape(y);
}
}
}
</script>
This will detect if a user is on a device with a screen width of less than 699 pixels, or if they have gone to the .mobi domain of your site (if you have one). To allow the user to go back to the desktop site, create a link somewhere on your mobile page
<a href="http://www.MyWebsite.com/?skipmobile=1">
This will create a cookie notifying the site to go stay on the desktop site for that user. Based on the same logic, I believe putting the following link on the desktop site will change this cookie to allow the user to go back to the mobile site.
<a href="http://www.MyWebsite.com/?skipmobile=-1">
Note that I do not know much about cookies and have not tested this. If someone with more knowledge can verify, or correct, the second link, I would appreciate it, and I'm sure gs2rom would as well.
You can use Cookies. For exemple, set a Cookie when the user selects "desktop version", an when the user comes back check if it exists or not.
How to set a Cookie in PHP here (http://www.w3schools.com/php/php_cookies.asp)

Disable Snippet of HTML IF User is On iPad or Mobil Device?

I'd like to disable a snippet of HTML on iPads and mobile devices. This part of my site doesn't work on small screens... Any way to do it?
Thanks,
Tara
Javascript solves your problem, look this:
var isIpad = navigator.platform.indexOf("iPad") != -1,
isIphone = navigator.platform.indexOf("iPhone") != -1,
isIpod = navigator.platform.indexOf("iPod") != -1;
Yes, use the User-Agent header to detect if your user is coming from iPhone/iPad/MobileDevice. Then just don't output that piece of HTML.
You can use WURFL database to check for mobile devices capabilities.

Is it possible to completely deny a particular web browser from accessing a web application?

I've been doing a lot of cross-browser testing and I must say that it is the bane of my existence. My beautiful fonts are sullied in particular browsers and particular environments. Despite having the exact same code in two separate browsers, content is rendered in entirely different ways. This is no secret, of course. But what I'm wondering is if there is a way to literally block access to an HTML page from users with particular browsers?
<!--[if IE/Safari/Firefox/Chrome/Opera/etc]>
<link rel="stylesheet" href="/stylesheets/block.css" type="text/css" />
<![endif]-->
block.css
body { display: none; }
Professionally, I'm obligated to support all the browsers and environments that my users might feel they want to use. And it's really not so bad to learn how and why each browser acts the way that it does. But for side projects, it would be kind of nice to not have to worry about whether or not I will be shunned from society for not supporting browser x.
Also note that I didn't call out a particular browser as being particularly deficient, so please feel free to leave out any "browser x sucks!" comments.
There are several ways to do this:
You could do this with your web server (I don't know what you're using)
You could do this in your server code (again, not sure what you're using)
You could do this with JavaScript:
if(<BROWSER SUCKS>) {
window.location = "YOUR-ERROR-PAGE.html";
}
Or
if(<BROWSER SUCKS>) {
alert("Your browser sucks, use 'xyz' instead.");
}
Your code would need to look at the window.navigator object to detect the browser type.
Specifically with regards to your example above, to hide the page if the browser sucked, you would use:
document.body.style.display = "none";
Yes, probably, but it's not feasible as any modern browser will let you change the user-agent string and thus (likely) bypass your checks.
You could use something like:
<?php
$using_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== FALSE);
if($using_ie6) {
die('Sorry, your browser is not supported');
}
?>
and modify according to which browser you wish to block, the above obviously would allow you to block IE6.
You can use http://www.useragentstring.com/ to help

How to mark-up phone numbers?

I want to mark up a phone number as callable link in an HTML document. I have read the microformats approach, and I know, that the tel: scheme would be standard, but is quite literally nowhere implemented.
Skype defines, as far as I know, skype: and callto:, the latter having gained some popularity. I assume, that other companies have either other schemes or jump on the callto: train.
What would be a best practice to mark-up a phone number, so that as many people as possible with VoIP software can just click on a link to get a call?
Bonus question: Does anyone know about complications with emergency numbers such as 911 in US or 110 in Germany?
Update: Microsoft NetMeeting takes callto: schemes under WinXP. This question suggests, that Microsoft Office Communicator will handle tel: schemes but not callto: ones. Great, Redmond!
Update 2: Two and a half years later now. It seems to boil down to what you want to do with the number. In mobile context, tel: is the way to go. Targeting desktops it's up to you, if you think your users are more Skype people (callto:) or will more likely have something like Google Voice (tel:) installed. My personal opinion is, when in doubt use tel: (in line with #Sidnicious' answer).
Update 3: User #rybo111 noted, that Skype in Chrome has meanwhile jumped on the tel: bandwagon. I cannot verify this, because no machine with both at hand, but if it's true, it means we have finally a winner here: tel:
The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.
callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.
Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .
Example:
1-847-555-5555
My test results:
callto:
Nokia Browser: nothing happens
Google Chrome: asks to run skype to call the number
Firefox: asks to choose a program to call the number
IE: asks to run skype to call the number
tel:
Nokia Browser: working
Google Chrome: nothing happens
Firefox: "Firefox doesnt know how to open this url"
IE: could not find url
The best bet is to start off with tel: which works on all mobiles
Then put in this code, which will only run when on a desktop, and only when a link is clicked.
I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer
if (!jQuery.browser.mobile) {
jQuery('body').on('click', 'a[href^="tel:"]', function() {
jQuery(this).attr('href',
jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
});
}
So basically you cover all your bases.
tel: works on all phones to open the dialer with the number
callto: works on your computer to connect to skype from firefox, chrome
As one would expect, WebKit's support of tel: extends to the Android mobile browser as well - FYI
I keep this answer for "historic" purpose but don't recommend it anymore. See #Sidnicious' answer above and my Update 2.
Since it looks like a draw between callto and tel guys, I want to throw in a possible solution in the hope, that your comments will bring me back on the way of light ;-)
Using callto:, since most desktop clients will handle it:
call me
Then, if the client is an iPhone, replace the links:
window.onload = function () {
if (navigator.userAgent.match (/iPhone/i)) {
var a = document.getElementsByTagName ("a");
for (var i = 0; i < a.length; i++) {
if (a[i].getAttribute ('href').search (/callto:/i) === 0) {
a[i].setAttribute ('href', a[i].getAttribute ('href').replace (/^callto:/, "tel:"));
}
}
}
};
Any objections against this solution? Should I preferably start from tel:?
Mobile Safari (iPhone & iPod Touch) use the tel: scheme.
How do I dial a phone number from a webpage on iPhone?
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
this worked for me:
1.make a standards compliant link:
<a href="tel:1500100900">
2.replace it when mobile browser is not detected, for skype:
$("a.phone")
.each(function()
{
this.href = this.href.replace(/^tel/,
"callto");
});
Selecting link to replace via class seems more efficient.
Of course it works only on anchors with .phone class.
I have put it in function if( !isMobile() ) { ... so it triggers only when detects desktop browser. But this one is problably obsolete...
function isMobile() {
return (
( navigator.userAgent.indexOf( "iPhone" ) > -1 ) ||
( navigator.userAgent.indexOf( "iPod" ) > -1 ) ||
( navigator.userAgent.indexOf( "iPad" ) > -1 ) ||
( navigator.userAgent.indexOf( "Android" ) > -1 ) ||
( navigator.userAgent.indexOf( "webOS" ) > -1 )
);
}
I used tel: for my project.
It worked in Chrome, Firefox, IE9&8, Chrome mobile and the mobile Browser on my Sony Ericsson smartphone.
But callto: did not work in the mobile Browsers.
I would use tel: (as recommended). But to have a better fallback/not display error pages I would use something like this (using jquery):
// enhance tel-links
$("a[href^='tel:']").each(function() {
var target = "call-" + this.href.replace(/[^a-z0-9]*/gi, "");
var link = this;
// load in iframe to supress potential errors when protocol is not available
$("body").append("<iframe name=\"" + target + "\" style=\"display: none\"></iframe>");
link.target = target;
// replace tel with callto on desktop browsers for skype fallback
if (!navigator.userAgent.match(/(mobile)/gi)) {
link.href = link.href.replace(/^tel:/, "callto:");
}
});
The assumption is, that mobile browsers that have a mobile stamp in the userAgent-string have support for the tel: protocol. For the rest we replace the link with the callto: protocol to have a fallback to Skype where available.
To suppress error-pages for the unsupported protocol(s), the link is targeted to a new hidden iframe.
Unfortunately it does not seem to be possible to check, if the url has been loaded successfully in the iframe. It's seems that no error events are fired.
Since callto: is per default supported by skype (set up in Skype settings), and others do also support it, I would recommend using callto: rather than skype: .
Although Apple recommends tel: in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto: just the same. So I recommend using callto: on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.
Update (June 2013)
This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel: and callto: links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel: links while mobile Android doesn't do anything with callto: links. Even Google Chrome with the Google Talk plugin does not respond to tel: links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel: links to work on their computer.
If the site design dictated that I only provide one link, I'd use a tel: link that I would try to change to callto: on desktop browsers.
Using jQuery, replace all US telephone numbers on the page with the appropriate callto: or tel: schemes.
// create a hidden iframe to receive failed schemes
$('body').append('<iframe name="blackhole" style="display:none"></iframe>');
// decide which scheme to use
var scheme = (navigator.userAgent.match(/mobile/gi) ? 'tel:' : 'callto:');
// replace all on the page
$('article').each(function (i, article) {
findAndReplaceDOMText(article, {
find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
replace:function (portion) {
var a = document.createElement('a');
a.className = 'telephone';
a.href = scheme + portion.text.replace(/\D/g, '');
a.textContent = portion.text;
a.target = 'blackhole';
return a;
}
});
});
Thanks to #jonas_jonas for the idea. Requires the excellent findAndReplaceDOMText function.
I use the normal 12 34 56 markup and make those links non-clickable for desktop users via pointer-events: none;
a[href^="tel:"] {
text-decoration: none;
}
.no-touch a[href^="tel:"] {
pointer-events: none;
cursor: text;
}
for browsers that don't support pointer-events (IE < 11), the click can be prevented with JavaScript (example relies on Modernizr and jQuery):
if(!Modernizr.touch) {
$(document).on('click', '[href^="tel:"]', function(e) {
e.preventDefault();
return false;
});
}