Prevent JS errors when Layout Builder is not initially displayed but loaded later via ajax

Created on 8 April 2023, about 1 year ago
Updated 30 June 2023, 12 months ago

Problem/Motivation

Coming here from Layout Builder IPE β†’ , which loads the LB interface into the frontend via AJAX after user interaction. At the time when the initial entity page renders, some situations might require that the Gin LB javascript must already be included (I admit that this can be subjective and there might be other solutions), but gin_lb_preview_regions.js creates JS errors due to missing markup (no element with id #glb-toolbar-preview-regions). Given the nature of those errors I'd consider this issue as something that is easy enough to fix without any downsides. Fixing this makes it easier to build custom functionality on top of the Gin and Gin LB ecosystem.

Steps to reproduce

  • Clean Drupal install with Layout Builder, Gin and Gin LB enabled
  • Create a custom module with the following content that includes gin_lb/gin_lb_init
    /**
     * Implements hook_page_attachments().
     */
    function custom_module_page_attachments(array &$attachments) {
      $attachments['#attached']['library'][] = 'gin_lb/gin_lb_init';
    }
    
  • Open any page and see this in the browser console:
    Uncaught TypeError: Cannot read properties of null (reading 'checked')
        at gin_lb_js.js?v=9.5.7:1:3287
        at Array.forEach (<anonymous>)
        at Object.attach (gin_lb_js.js?v=9.5.7:1:3039)
        ...
    

Proposed resolution

Add a check to Drupal.behaviors.glb_preview_regions so that code runs only if the expected markup is present on the page.
I'll provide a patch.

Remaining tasks

Review and test.

User interface changes

None

API changes

None

Data model changes

None

✨ Feature request
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡©πŸ‡ͺGermany berliner

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.69.0 2024