Unable to copy credentials to clipboard in Rails app – JavaScript clipboard API issues

Problem:

I’m building a Ruby on Rails application that manages user credentials and allows users to share them securely. However, I’m running into an issue where I am unable to copy the credentials to the clipboard using JavaScript’s Clipboard API. I can generate a link (https only) to share the credentials, but the actual copying to the clipboard doesn’t seem to work. Setup:

Rails Version: 7.2.2
Ruby Version: 3.2.6
JavaScript: Using the Clipboard API to copy credentials to the clipboard.
Browser: Firefox.

Localhost

Clipboard API usage:
This code “works”, but it’s not what i want it to do, i just want to copy the credentials to the clipboard (later when it works, i will be doing some changes). But it just works if i do it with an URL.
I have a button in my app that, when clicked, generates a URL (just tested whatever website) with the credentials and attempts to copy this URL to the clipboard. Here’s the JavaScript I am using:

document.querySelectorAll(".share-credentials-btn").forEach(function(button) {
  button.addEventListener("click", function() {
    const unlocked = button.getAttribute("data-unlocked") === 'true';
    if (unlocked) {
      const username = button.getAttribute("data-username");
      const password = button.getAttribute("data-password");

      // Generate the URL to share credentials
      const passwordPusherLink = `https://www.passwordstore.com/push?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`;
      
      // Try to copy the URL to the clipboard
      navigator.clipboard.writeText(passwordPusherLink).then(function() {
        alert("Credentials copied to clipboard!");
      }).catch(function(error) {
        alert("Error copying credentials: " + error);
      });

      // Optionally open the link in a new window
      window.open(passwordPusherLink, "_blank");
    } else {
      alert("Unlock the credentials to share them.");
    }
  });
});

The issue: The function to copy text to the clipboard works in some cases, but not in others. Sometimes the text doesn’t get copied, and I receive an error message in the catch block. I’m also unsure if there’s any condition under which the Clipboard API will fail (e.g., browser security settings, pop-up blockers, etc.

What I’m trying to achieve: I need a reliable way to copy credentials to the clipboard when the user clicks a button. I want the credentials to be copied securely and seamlessly without requiring additional user input (like pressing CTRL+C). So, i am new in rails and js, making a new project to learn and would appreciate some help. Thanks.