How to use mobile detect

Hm, I did a quick test with my plugin and a fresh langkit and it works as expected.

With this code, the line is echoed on desktop:

<?php
if(!detect()->isMobile()):
 echo "I'm on desktop";
endif;  ?>

If I remove the exclamation mark, it is not shown.

Also, if I change the User Agent, the line disappears as expected.

However, in general it is recommended not to use User Agent detection, because it is unreliable. And use Responsive Design instead.

What is your use case for detecting mobile? Aren’t media queries (CSS) usable?

Imho server side detection is always hacky and should be a last resort go-to tool (and if possible to be avoided).

1 Like

Which version are you running? I am on 2.5.6. I am trying to display different content snippets for desktop and mobile. And right now seeing the echo message in both mobile and desktop in chrome. Thats what my structure looks like, in case I am missing something.

21

Thank you!

Do you refresh the page when switching between Desktop and mobile View? For me it works in Chrome, but I have to refresh the browser for the User Agent change to take effect.

Tested with 259 RC-2, but that shouldn’t make any difference.

It wont help you load snippets based on device of course, but it is safer to use media queries. You can always use Modernizr + Detectizer to detect devices. Personally I prefer Head.js for this but forward development stopped some time ago. Use at your peril.

I just also tried it with the langkit https://github.com/getkirby/langkit and facing same problem here. And yes, I refresh the page when switching between desktop and mobile view.

1 Like

In web development nowadays device sniffing and showing different content on the same URL is frowned upon. That’s why most plugins don’t work properly anymore (if they ever did…) because nobody invests time to update them any longer.

In general everyone jumped the reponsive design (CSS media queries) train, which solves a lot of these issues. If you have to support different versions of the site, my advice is to build a whole separate version and serve the same content with different templates on a different subdomain (m.domain.com e.g.) for mobile devices. But even that feels icky to me.

2 Likes