Koala7
Koala7

Reputation: 1404

Button Copy to Clipboard window location href

I want to copy the current window.location.href onClick in the button, even if i set the right state i can not actually copy it, what is my problem?

Here the code

const [copyHref, setCopyHref] = useState(JSON.stringify(window.location.href));

  const copyToClipboard = () => {
    setCopyHref(copyHref)
    document.execCommand(copyHref);
    alert("Copied the text: " + copyHref);
  };

<Button onClick={copyToClipboard}/>

When i click i get the alert with the right url, but it does not actually copy it. How can i do that?

Upvotes: 0

Views: 1680

Answers (3)

codemonkey
codemonkey

Reputation: 7905

window.location.href, to the best of my knowledge, is a string. So I am not quite sure what your goal is with JSON.stringify(window.location.href).

I am also puzzled as to your use of the state to accomplish this basic function.

As for copying the URL into clipboard, I would accomplish it like so:

export default function App() {
  const copyToClipboard = () => {
    navigator.clipboard.writeText(window.location.href).then(function() {
      alert("copied successfully!")
    }, function(err) {
      alert('Failed to copy');
    });
  };

  return (
    <div className="App">
      <button onClick={copyToClipboard}> copy </button>    
    </div>
  );
}

Upvotes: 1

xflorin94
xflorin94

Reputation: 133

Try like this:

const copyToClipboard = () => {
 navigator.clipboard.writeText(copyHref);
 alert("Copied the text: " + copyHref);
};

Upvotes: 0

Guy Berkovich
Guy Berkovich

Reputation: 61

The function execCommand does not work like this. You need to specify which command to execute and it not specifically for copying. Please refer to https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard for more details. Also you can use the native js function copy() for this.

Upvotes: 0

Related Questions