How to Copy to Clipboard

Asked 1 years ago, Updated 1 years ago, 25 views

https://rubygems.org/gems/i18n/versions/0.7.0

On the right side of this site, there is a button to copy the text to the clipboard.

If you look at html, there are the target characters in the data attribute, but how do you copy them?

Is it possible with JavaScript?

javascript

2022-09-30 19:31

2 Answers

Copy and paste from Javascript is available, but it doesn't work consistently across all browsers.Because the clipboard is shared between local applications used by the user, if the web page can browse or change the clipboard, there is a risk that the user's work will be leaked through the web page script.As a result, clipboard operations from web pages are strictly restricted.Each browser has an API to browse and modify the clipboard, but it requires special permissions and the API usage restrictions vary depending on the version, so it is impossible to handle the clipboard stably.

If you look at the source of the rubygems site, you can see that the library uses zeroclipboard.This is to launch Flash content that does not appear on the page and provide copy functionality via the Flash API.

From Javascipt, the API handling the clipboard has been drafted by W3C as Clipboard API and events.The way it works is that when a user performs a copy and paste operation, the event handler refers to the contents of the Clipboard.The security restriction is lifted only when the user copies and pastes the web page.However, this API is only supported by Firefox among the most popular browsers available today.Not all browsers support it.

Because security is tight and browser functionality is not stable, Flash copy and paste functionality instead of Javascript has become the mainstream for copy and paste.I remember that zeroclipboard became popular when GitHub started using.I used this before.Flash also has the user copy and paste operations or button click moments to gain copy and paste permission.That's why it's implemented with such a copy button.


2022-09-30 19:31

You use zeroclipboard for that page. The designation is done in Javascript, but Flash is used internally.

https://github.com/zeroclipboard/zeroclipboard

HTML in this usage sample also specifies data-clipboard-text. The text specified here is copied.

You can also have the data-clipboard-target attribute copy the contents of another tag. (That's why the contents of Textarea are copied on the first link.)

<html>
  <body>
    <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
    <script src="ZeroClipboard.js"></script>
    <script src="main.js"></script>
  </body>
</html>


2022-09-30 19:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.