userfunc condition for detecting mobile device

2.3k views Asked by At

Since TYPO3 7 the condition 'device' and 'useragent' are deprecated. No I'm looking for a userFunc to use as a condition for detecting mobile devices. My aim is to hide or to show some special pages on mobile devices. I used the extension 'contexts_wurfl' for a while but I guess that there should be 'smaller solutions'.

Thanks for any help.

2

There are 2 answers

2
Arek van Schaijk On BEST ANSWER

You can accomplish this with TypoScript using the PAGE Object.

The code below shows you how to execute your own code before executing something else (like the template engine/content rendering etcetera).

page.01 = USER_INT
page.01 {
    userFunc = TYPO3\MyExt\Utility\MobileDeviceUtility->detectMobileDevice
}

And in code:

<?php
namespace TYPO3\MyExt\Utility;

class MobileDeviceUtility {

    /**
     * Is Mobile Device
     *
     * @return boolean
     */
    static public function isMobileDevice() {

        // calculates if the user agent is on a mobile device

        return TRUE;
    }

    /**
     * Detect Mobile Device
     *
     * @param string $content
     * @param array $conf
     * @return void
     */ 
    static public function detectMobileDevice($content, array $conf = NULL) {

        global $TSFE;

        if (self::isMobileDevice()
              && (boolean) $TSFE->page['mycustom_device_checkbox']
        ) {
            // do something 
        }

    }

}

OR otherwise you should create your own condition [YourVendor\YourPackage\YourCondition = var1 = value1, var2 != value2, ...].

0
Lukas L. On

If you would like to avoid writing a custom user function the globalString function of Typo3 can still be used in the later versions of Typo3 to access the useragent and other information like this:

[globalString = IENV:HTTP_USER_AGENT = *<User-Agent>*]
  # Statements here will only affect browsers with the useragent matching <User-Agent>
[else]
  # Statements here will only affect browsers with the useragent not matching <User-Agent>
[end]

Detailed documentation for conditions using globalStringcan be found here.

A Full list of variables that can be used with the globalString function can be found here.

To execute different typoscript for mobile and stationary devices I found the following snippet to be working for Typo3 8.7 LTS and 9.5 LTS:

[globalString = IENV:HTTP_USER_AGENT = *Android*]||[globalString = IENV:HTTP_USER_AGENT = *iPhone*]||[globalString = IENV:HTTP_USER_AGENT = *Mobile*]||[globalString = IENV:HTTP_USER_AGENT = *Windows Phone*]
  # Statements for mobile devices only
[else]
  # Statements for stationary devices only
[end]