Detect Responsive States in WordPress Block Editor or Site Editor

This event __experimentalGetPreviewDeviceType merged to the core in May 2024.

This event data outputs breakpoint preview on editor depending on the selected state.


add_action( 'admin_print_footer_scripts', function() {
    // Only run this on the block editor screens
    $screen = get_current_screen();
    if ( ! $screen || ! $screen->is_block_editor() ) {
        return;
    }
    ?>
    <script type="text/javascript">
        // wp.domReady waits until the editor is fully loaded
        window.onload = function() {
            if ( typeof wp !== 'undefined' && wp.domReady ) {
                wp.domReady( function() {
                    let lastState = '';
                    
                    // Subscribe to data changes
                    wp.data.subscribe( function() {
                        // Check both Post Editor and Site Editor stores
                        const editPost = wp.data.select( 'core/edit-post' );
                        const editSite = wp.data.select( 'core/edit-site' );
                        
                        const currentState = editPost 
                            ? editPost.__experimentalGetPreviewDeviceType() 
                            : ( editSite ? editSite.__experimentalGetPreviewDeviceType() : 'Desktop' );

                        if ( currentState !== lastState ) {
                            console.log( 'Device View Changed To:', currentState );
                            lastState = currentState;
                        }
                    } );
                } );
            }
        };
    </script>
    <?php
}, 100 );