How to mark-up phone numbers? - html

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;
});
}

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)

How to pre-populate the sms body text via an html link

How to use an html link to open the sms app with a pre-filled body?
Everything I have read seems to indicate that sms:18005555555?body=bodyTextHere
Should work, but on the iPhone, this doesn't work. If I take out the ?body=bodyTextHere, and just use sms:phonenumber, it works.
I have seen several instances where QR codes do this through a safari link. How are they able to pre-populate the body text?
It turns out this is 100% possible, though a little hacky.
If you want it to work on Android you need to use this format:
Link
If you want it to work on iOS, you need this:
Link
Live demo here: http://bradorego.com/test/sms.html (note the "Phone and ?body" and "Phone and ;body" should autofill both the to: field and the body text. View the source for more info)
UPDATE:
Apparently iOS8 had to go and change things on us, so thanks to some of the other commenters/responders, there's a new style for iOS:
Link
(phone number is optional)
I know this is an old thread but stumbled upon it and found that some parts are no longer relevant.
I've found that if you want to just per-populate the text without adding a phone number, you can do the following:
sms:?&body=/* message body here */
For iOS 8, try this:
Link
Switching the ";" with a "&" worked for me.
Just put all of the symbols in this order (I only tested it in this order since it makes the most sense code-wise to me).
Notice for the body link... I just put... ;?&body=. Also, notice that I have found I needed to use %20 for any spaces.
I have tested it on my iphone (v. 9.2) and another android and it works just fine.
This will solve the issue with having to hack it for different devices. I have no artifacts when I tested it in the SMS.
Send me SMS
There is not need for two separate anchor tags for Android and iOS.
This should help.
// Without Contact Number
Text Message
// With Contact Number
Text Message
// Works on both Android and iOS
Android and iOS body only:
Only body
Android and iOS one recipient only with body:
one recipient only with body
Only Android multiple recipients with body:
Android multiple recipients with body
Only iOS multiple recipients with body:
iOS multiple recipients with body
Note that the body should be URI encoded.
We found a proposed method and tested:
Send SMS
Here are the results:
iPhone4 - fault (empty body of message);
Nokia N8 - ok (body of message - "Hello my friend", To
"12345678");
HTC Mozart - fault (message "unsupported page" (after click on the
"Send sms" link));
HTC Desire - fault (message "Invalid recipients(s):
<12345678?body=Hellomyfriend>"(after click on the "Send sms" link)).
I therefore conclude it doesn't really work - with this method at least.
For those wanting a solution that works in 2022 I set up a small web app that just uses the correct format for iOS, macOS, and Android automatically.
https://copy.gives/18005555555?body=Body+text+here
The issue in 2022 is that on iOS you * must * use double slashes as well as /&
So the respective working URLs are the following
sms://18005555555/&body=Body%20text%20here - iOS and macOS
sms://18005555555/?body=Body%20text%20here - Android
Notice the /& for Apple devices and /? for Android
You can try some working examples here(doesn't work embedded):
https://jsfiddle.net/thatguysam/swLtjh0q/
To get sms: and mailto: links to work on both iPhone and Android, without any javascript, try this:
click to text
click to email
I tested it on Chrome for Android & iPhone, and Safari on iPhone.
They all worked as expected.
They worked without the phone number or email address as well.
For using Android you use below code
<a href="sms:+32665?body=reg fb1>Send SMS</a>
For iOS you can use below code
<a href="sms:+32665&body=reg fb1>Send SMS</a>
below code working for both iOs and Android
<a href="sms:+32665?&body=reg fb1>Send SMS</a>
Bradorego's solution is what worked for me, but here is a more expanded answer.
A small consideration is that you need to encode the body using %20 instead of +. For PHP, this means using rawurlencode($body) instead of urlencode($body). Otherwise you'll see plus signs in the message on old versions of iOS, instead of spaces.
Here is a jQuery function which will refit your SMS links for iOS devices. Android/other devices should work normally and won't execute the code.
HTML:
SMS "Hello World" to 555-123-1234
jQuery:
(function() {
if ( !navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ) return;
jQuery('a[href^="sms:"]').attr('href', function() {
// Convert: sms:+000?body=example
// To iOS: sms:+000;body=example (semicolon, not question mark)
return jQuery(this).attr('href').replace(/sms:(\+?([0-9]*))?\?/, 'sms:$1;');
});
})();
Consider using a class like a.sms-link instead of a[href^="sms:"] if possible.
<a href="###" data-telno="13800000000" data-smscontent="hello" class="XXXXX XXXXXX XXXXXX sendsms"/>
$('.sendsms').on('click', function(){
var p = $(this).data('telno'),
c = $(this).data('smscontent'),
t = ';';
if (!ios) { // add your own iOS check
t = '?';
}
location.href = 'sms:'+ p + t + c;
})
The iPhone doesn't accept any message text, it will only take in the phone number. You can see this here https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/SMSLinks/SMSLinks.html#//apple_ref/doc/uid/TP40007899-CH7-SW1
Link
This works on my iPhone 5S!
I suspect in most applications you won't know who to text, so you only want to fill the text body, not the number. That works as you'd expect by just leaving out the number - here's what the URLs look like in that case:
sms:?body=message
For iOS same thing except with the ;
sms:;body=message
Here's an example of the code I use to set up the SMS:
var ua = navigator.userAgent.toLowerCase();
var url;
if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1)
url = "sms:;body=" + encodeURIComponent("I'm at " + mapUrl + " # " + pos.Address);
else
url = "sms:?body=" + encodeURIComponent("I'm at " + mapUrl + " # " + pos.Address);
location.href = url;
Well not only do you have to worry about iOS and Android, there's also which android messaging app. Google messaging app for Note 9 and some new galaxys do not open with text, but the samsung app works. The solution seems to be add // after the sms:
so sms://15551235555
Link
should be
Link
(Just a little bit of topic), but maybe if you searched you could stumble here...
In markdown (tested with parsedown and on iOS / android) you could do :
[Link](sms:phone_number,?&body=URL_encoded_body_text)
//[send sms](sms:1234567890;?&body=my%20very%20interesting%20text)
Was struggling with ability to open SMS app with body only message, no recipients on iOS 11+.
None of the solutions above worked for me, it didn't open at all or opened with something pre-populated in recipients (like ';').
Finally I ended up with this syntax for body only:
sms:///?body=Hello%20World
Used up to iOS 14, worked fine!
?body= //for Android
&body= //for iOS
I found out that, on iPhone 4 with IOS 7, you CAN put a body to the SMS only if you set a phone number in the list of contact of the phone.
So the following will work If 0606060606 is part of my contacts:
Send SMS
By the way, on iOS 6 (iPhone 3GS), it's working with just a body :
Send SMS
Every OS version has a different way of doing it. Take a look at the sms-link library
universal link use tel &? body
link ios+android
https://output.jsbin.com/puqicel
link ios+android
link ios+android
One of the problems with a click-to-text link is solving the desktop scenario where no native texting app exists. A solution is to use Zipwhip's Click-to-Text button creator.
On the desktop, they send you an actual real text message behind the scenes from the user's input.
On iOS or Android you get the native texting functionality instead.
https://www.zipwhip.com/create-sms-button/
Neither Android nor iPhones currently support the body copy element in a Tap to SMS hyperlink.
It can be done programmatically though,
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
picker.recipients = [NSArray arrayWithObject:#"48151623"];
picker.body = #"Body text.";
[self presentModalViewController:picker animated:YES];
[picker release];

Make sure <a href="local file"> is opened outside of browser

For an Intranet web application (document management), I want to show a list of files associated with a certain customer. The resulting HTML is like this:
somefile.docx
somefile.pdf
yetanotherfile.txt
This works fine. Unfortunetly, when clicking on a text file (or image file), Internet Explorer (and I guess most other browsers as well) insist on showing it in the browser instead of opening the file with the associated application (e.g. Notepad). In our case, this is undesired behavior, since it does not allow the user to edit the file.
Is there some workaround to this behavior (e.g. something like <a href="file:///..." open="external">)? I'm aware that this is a browser-specific thing, and an IE-only solution would be fine (it's an Intranet application after all).
Do you WANT people to just mess around with things lying on your server? That reeks of lack of security to me...
I'd recommend letting the user check it out locally and using a database or similar to allow people to check in new drafts. Said drafts should be verified and validated somehow before they are actually written to the server's filesystem.
I just tested this and it seems to work (IE6, not in FF or Chrome):
<HTML>
<script language="JavaScript">
function startWord(strFile)
{
var myApp = new ActiveXObject("Word.Application");
if (myApp != null)
{
myApp.Visible = true;
myApp.Documents.Open(strFile);
}
}
</script>
test.doc.
Found it here.

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

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