Skip to main content

Make QR codes and copy buttons work in a block or Elementor preview

Free Intermediate

For anyone wrapping [benecaster_qr_code], the feed URL widget or [benecaster_episode_share] in a block or an Elementor widget. Enqueueing benecaster-frontend loads Benecaster’s front-end script, but the script wires widgets once, when the page loads — markup a preview inserts later is missed, so the QR Code preview shows its frame and nothing in it, and copy buttons do nothing.

Call window.benecasterFrontend.init( root ) after the markup arrives. It is safe to call repeatedly on the same markup, and calling it after every re-render is the intended use.

Load the script in the editor first. Enqueue benecaster-frontend from enqueue_block_assets, guarded by is_admin() — see Load Benecaster’s front-end styles into the block editor.

Do not copy Benecaster’s initialisers into your own script to get the same effect. They carry behaviour that has to stay in one place — after a subscriber resets their feed token, an old feed URL must never come back onto the screen.

It does not count plays. The web player’s play beacon is deliberately left out, so a preview re-rendering in the editor does not inflate a show’s numbers.

Code

// Block editor: ServerSideRender replaces its markup after every attribute
// change, so re-run on each change. init() is idempotent; calling it often is
// the intended use.
const observer = new MutationObserver( () => window.benecasterFrontend?.init( wrapper ) );
observer.observe( wrapper, { childList: true, subtree: true } );

// Elementor: run for each widget instance when Elementor renders it, in the
// editor and on the live page alike. $scope is the widget's own element,
// which init() accepts directly.
jQuery( window ).on( 'elementor/frontend/init', () => {
    elementorFrontend.hooks.addAction(
        'frontend/element_ready/my-benecaster-qr.default',
        ( $scope ) => window.benecasterFrontend?.init( $scope[ 0 ] )
    );
} );

View on GitHub →

Need this built rather than just documented? See our services →