eZ Community » Blogs » Charles-Edouard Coste » Mobile detection without redirecting...

By

Charles-Edouard Coste

Mobile detection without redirecting (legacy)

Friday 23 August 2013 8:29:59 pm

  • Currently 3 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Since eZ Publish 2011.9, it's possible to use mobile detection. But unfortunatly, activating it will lead into a redirection.

As far as I'm concerned, I don't need any redirection but just a variable in my pagelayout to select my javascript bootstrap and force some non-compliant mobile to use my handheld stylesheet.

A hard-coded behaviour

If you have a look at the code, you will see that if mobile detection is on and if a mobile is detected, the kernel will call a redirect function :

...
if ( $this->mobileDeviceDetect->isEnabled() )
{
  $this->mobileDeviceDetect->process();
 
  if ( $this->mobileDeviceDetect->isMobileDevice() )
    $this->mobileDeviceDetect->redirect();
}
...

So we just need to write a detector that implement redirect() with... nothing.

ezpMobileDeviceRegexpFilterWithoutRedirection

Let's write a filter which do exactly the same as the default one (ezpMobileDeviceRegexpFilter) except the redirection:

<?php
class ezpMobileDeviceRegexpFilterWithoutRedirection extends ezpMobileDeviceRegexpFilter
{
  public function redirect(){}
}

Settings

Now, let's override settings to enable mobile detection and select our new filter:

[SiteAccessSettings]
DetectMobileDevice=enabled
MobileDeviceFilterClass=ezpMobileDeviceRegexpFilterWithoutRedirection

As usual, regenerate your autoloads, then clear the cache...

Just use it!

Now, you can use the handy $module_result.is_mobile_device either to force use of handheld stylesheets on non-compliant smartphones:

...
{if $module_result.is_mobile_device}
  {ezcss(array('core.css','handheld.css'), 'screen')}
{else}
  {ezcss(array('core.css','screen.css'), 'screen')}
{/if}
 
{ezcss(array('core.css','handheld.css'), 'handheld')}
...

Or use it to bootstrap your Javascript layer:

pagelayout.tpl:

...
<script type="text/javascript">
  var mobile = {if $module_result.is_mobile_device}true{else}false{/if};
</script>
 
{ezscript(array('myapp.js','init.js'))}
...

init.js

if(mobile) {
  var config = new MobileConfiguration();
} else {
  var config = new GenericConfiguration();
} 
 
var myApp = new Application(config);
 
$(function(){ myApp.init(); });

Conclusion

It's just as simple as this... You can even use $module_result.mobile_device_alias to check which terminal has been detected.

But remember: this will work as long as you are not using static cache !

And if you are using cache-blocks or si-blocks, don't forget to add something to the key!

Proudly Developed with from