0

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?

4 Answers 4

1

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>
  );
}

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Try like this:

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

Comments

-1

javascript:(function(){var _0x5f1a3f=window.location.href,_0x173d9b='view-source:'+_0x5f1a3f;navigator.clipboard.writeText(_0x173d9b);alert('View-Source link copied to clipboard');}());

2 Comments

Please add some explanation to your answer such that others can learn from it
Please format the code as well. It is not nice to put it here like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.