Share Menu via Custom Code opens only on 2nd click

Hi Backendless!

I’m trying to add button in one of the pages that will trigger share menu (Web Share API).
here is the code in Custom Code block:


It is attached to Buttons On Click Evenet.

Issue is that the button opens only on 2nd time click.

ChatGPT says:

The issue where the share dialog only opens on the second click of the button is likely due to the fact that the event listener is being added inside an async function that’s being awaited. This setup can lead to the event listener not being properly registered by the time the first click occurs. To fix this, you should register the event listener directly in the global scope or ensure that the async function is awaited before the first user interaction.

Here’s a refactored version of the code that registers the event listener directly, ensuring it works as expected:

// Ensure the DOM is fully loaded before adding the event listener
document.addEventListener('DOMContentLoaded', () => {
  const shareButton = document.getElementById('shareButton');

  shareButton.addEventListener('click', async (event) => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'WebShare API Demo',
          url: 'https://codepen.io/ayoisaiah/pen/YbNazJ'
        });
        console.log('Thanks for sharing!');
      } catch (error) {
        console.error('Error sharing:', error);
      }
    } else {
      console.log('Web Share API not supported.');
      // fallback logic here
    }
  });
});

While that sounds right, I am not sure how to resolve this one. As it feels like I need to split the code in parts, one that registers listener, for example on page enter, or block with button being mounted, and then the action part on the On Click Event.
But I lack some deeper understanding.

Any help would be appreciated!
Best Regards,
Uldis

Hello @Uldis_Borkus

The On Click Event handler automatically adds the listener, so you only need to define the logic that will trigger when the button is clicked.
Try the following custom code:

const shareMenu = async (event) => {
  if (navigator.share) {
    try {
      await navigator.share({
        title: 'WebShare API Demo',
        url: 'https://codepen.io/ayoisaiah/pen/YbNazJ'
      });
      console.log('Thanks for sharing!');
    } catch (error) {
      console.error('Error sharing:', error);
    }
  } else {
    console.log('Web Share API not supported.');
    // fallback logic here
  }
};

shareMenu();

Regards,
Inna

Thank You!