如果特定块处于活动状态,古腾堡编辑器会检查 JS

Gutenberg editor check in JS if specific block is active

我正在编辑器中使用自定义 JS 注册一个块:

function my_block_assets() {

  wp_register_script(
    'my-block-js', // 
    plugins_url( '/dist/my-block.js', dirname( __FILE__ ) ),
    array( 'jquery' ),
  );

  register_block_type(
    'custom/my-block', array(
      'style'         => 'my-block-css',        
      'editor_style'  => 'my-block-editor-css',
      'editor_script' => 'my-block-js',
    )
  );

}

add_action( 'init', 'my_block_assets' );

我想 运行 我的自定义 JS 仅当自定义块被添加到编辑器中时。我这样做:

$(window).on('load', function () {      
  var container = document.querySelector('.wp-block-custom-my-block');

  if ( container ) {
    // run custom js
  }
});

这似乎可行,但速度可能很慢。是否有任何特殊的 JS 函数可以用来检查是否在编辑器中添加了块?我找到了使用 has_block() 在前端检查 PHP 中的块的方法,但在编辑器中没有检查 JS 的方法。

您可以 select 来自 Block Data Module 的许多块特定数据。也就是说,以下在后端工作:

if ( wp.data.select('core/blocks').getBlockType('custom/my-block') ) { 
  //run custom js 
}

Doc of getBlockType.

关于前端,我将使用 has_block 函数:

<?php 
mycustomblock_frontend_scripts() {
    if ( has_block( 'custom/my-block' ) ) {
        wp_enqueue_script('my-block-frontend-script');
    }
}
add_action( 'wp_enqueue_scripts', 'blockgallery_frontend_scripts' );