Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when the device emulation mode is turned on or off in Chrome

Chrome DevTools has the option to use the device emulation mode.

I know there's a way to test whether the mode is on or not. But I'd like to know when it's being activated or deactivated, on click.

Are there any events I could listen to, fired by the browser, that indicate the mode was turned on or off?

like image 577
lesssugar Avatar asked Nov 25 '25 07:11

lesssugar


2 Answers

I ended up doing this:

$(window).on('orientationchange', function(e) {

    if (e.tagret && e.target.devicePixelRatio > 1) {
        // Emulation mode activated
    } else {
       // Emulation mode deactivated
    }

});

Works for Google Chrome (my version: 58.0). Is it the bulletproof way? Not sure. It's enough for my needs, though.

orientationchange docs here.

like image 112
lesssugar Avatar answered Nov 26 '25 20:11

lesssugar


My solution:

$(window).on('orientationchange', function(e) {
    setTimeout(function() {
        var emulationModeActivated = window.navigator.userAgent.indexOf('Mobile') !== -1;
    }, 0);
});

Chrome adds Mobile to userAgent in device emulation mode, for example "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1"

e.target.devicePixelRatio isn't usable on Mac with Retina Display as value is always > 1

like image 45
Alex Belozerov Avatar answered Nov 26 '25 19:11

Alex Belozerov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!