views:

249

answers:

3

Hi friends,

I want to check whether my site is viewing in mobile or PC. If its mobile device, i need to redirect my site url; like Google does..

If possible Get me code in javascript

Please clarify my doubt.. How to check it browsed from mobile or PC..

+1  A: 

You typically use the User-Agent header to detect the browser.

Here's JavaScript code that does basically that (only for mainstream browsers though, you'd have to add the Mobile User-Agents)

http://www.quirksmode.org/js/detect.html

And here's a list of mobile browser identifiers

http://www.zytrax.com/tech/web/mobile_ids.html

The list is not complete and will never be, given the rate new mobiles appear on the market, but what I did back when I did it is to store all received user agents in a database, and then look for them to classify them as mobile and which brand/model.

What you can't rely on though is JavaScript, it's better done in server code (not all mobile browsers execute JavaScript).

There is a related question here on SO but I couldn't find it.

Vinko Vrsalovic
A: 

See this existing question.

You will have better luck doing this server side, as many mobile browsers don't even support JavaScript. Basically you want to check the user agent and compare to a list of known mobile browsers.

Greg
A: 

Here i got a simple answer for this query; This wont detect the mobile browser, but it redirect the page to our mobile.html page, through the following script;

find out the browser window size and redirect it..

winWidth=document.all?document.body.clientwidth:window.innderwidth; if (winwidth<800) { window.location.replace("mobile.html"); }