routing based on browser width

I have a site that's directed toward mobile use. As a result, the
basic structure consists of pages that render exclusively on mobile
devices, and then corresponding pages for desktop browsers that
explain that they need to come back on a mobile device.

Currently, I'm using Javascript on the mobile page to detect browser
width and then it redirects to the desktop page if it's above 480px

That works fine, but it's less than perfect when people link or
bookmark the desktop page, it never redirects back to the mobile one.
And, it seems to be less than perfect for search engines as well.

Here's what I've got now:

index.rhtml renders first and tosses this Javascript at it:

{ winWidth=document.all?document.body.clientWidth:window.innerWidth;
  if (winWidth > 481)
  location="<%= url_for({:controller => 'info', :action =>
'share_welcome', :id => @story, :only_path => false, :protocol =>
'http://'}) %>"

So you can see, it directs browsers over a certain width to, in this
case, share_welcome.rhtml

So, in a desktop browser, the index page looks like
share_welcome, while a mobile browser just sees

There's *got* to be a way to route this browser width logic ahead of
page load so that it's always no matter what, right?

Is it possible to build this into routes.rb somehow?

I'm stumped. Any ideas?

Thanks so much!


My browser (Firefox 3.5) does not send browser width-at-the-time
information in the request headers. I doubt any browsers do, so you
can't use this in any sort of routes or respond_to shinanagins.

If you need your application to perform differently depending on
different user agents, you need to relay on the User-Agent header.
This will of course require some research to find the UA's that your
app needs to consider as mobile devices, and be ready to respond to
user feedback when someone browses with a UA you did not anticipate.

Of course, if all that needs to change though is client-side behavior
(pages need to be rendered differently etc), perhaps reasoned and
judicious use of Javascript+CSS is the better approach.

This seems like an ultimately doomed strategy - the 480px limit you're
using is exactly met by the iPhone, the G1 and the Pre (in landscape),
and exceeded by the Kindle. Then there's the much-rumored "iPhone
tablet", which will completely exceed that if it ever appears.

It would seem more logical to either just show the pages to everybody,
or to detect user agents as others in the thread have suggested.

--Matt Jones

Seriously. Why bother disabling desktop browsers? I've seen a number
of mobile sites that render fine in any number of desktop browsers.

If you want to optimize layouts for particular browsers, you can turn
your layout call into a method. You can then put user-agent detection
there to render a particular layout customized for the particular
browser or device. If you really want to do redirection, it may be
possible to sneak that in there. I've never tried it myself, though.