- Работа с буфером обмена в JavaScript с использованием асинхронного API Clipboard
- Запись данных в буфер обмена
- Чтение данных из буфера обмена
- Практический пример
- Будущее API Clipboard
- Проверка возможностей браузера
- Итоги
- How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
- 7 Answers 7
- Windows script to copy some text to the clipboard?
- 5 Answers 5
- Copy text from a Windows CMD window to clipboard
- 8 Answers 8
Работа с буфером обмена в JavaScript с использованием асинхронного API Clipboard
Существует новое API JavaScript, предназначенное для организации асинхронного доступа к буферу обмена с использованием спецификации, которая всё ещё находится на этапе разработки. До сих пор в веб-разработке стандартным способом копирования текста в буфер обмена является подход, предусматривающий использование метода document.execCommand. Основной недостаток этого подхода заключается в том, что это — синхронная блокирующая операция. Асинхронное API для работы с буфером обмена основано на промисах, одной из его задач является устранение этого недостатка. Оно призвано дать веб-разработчикам более простое в использовании унифицированное API для работы с буфером обмена. Кроме того, это API спроектировано с учётом возможности поддержки множества типов данных, а не только text/plain.
Запись данных в буфер обмена
Запись данных в буфер обмена — простая операция, реализуемая посредством вызова метода writeText объекта clipboard с передачей ему соответствующего текста.
Чтение данных из буфера обмена
Для того чтобы прочитать данные из буфера обмена, используется метод readText . В целях повышения безопасности, помимо того, что страница, читающая данные из буфера обмена, должна быть открыта в активной вкладке браузера, пользователь должен предоставить ей дополнительное разрешение. Браузер автоматически запросит это разрешение при первом вызове readText .
Практический пример
Разберём простой пример взаимодействия с буфером обмена из JavaScript. Он будет работать лишь в поддерживаемых браузерах. Если хотите, можете своими силами доработать его, добавив механизмы, позволяющие ему функционировать в браузерах, которые пока не поддерживают API Clipboard. Посмотреть, как всё это работает, можно на странице оригинала статьи, в разделе Simple Demo.
А вот — JS-код, который отвечает за работу с буфером обмена.
Как видите, всё тут устроено очень просто. Единственное место, над которым пришлось немного поработать — это код для работы с кнопкой копирования, где мы сначала проверяем, что нам есть что копировать, а затем ненадолго меняем текст кнопки и очищаем поле ввода после успешного завершения операции копирования.
Будущее API Clipboard
Рассматриваемое API описывает более общие методы write и read , позволяющие работать с данными, отличающимися от обычного текста, в частности — с изображениями. Например, использование метода read может выглядеть так:
Обратите внимание на то, что эти методы пока не поддерживаются ни одним из существующих браузеров.
Проверка возможностей браузера
Предположим, вы создали веб-проект, некоторые функции которого полагаются на возможности по работе с буфером обмена. Учитывая то, что API Clipboard в настоящий момент поддерживает лишь один браузер, в подобном проекте нелишним будет предусмотреть альтернативные способы работы с буфером обмена. Например — метод, основанный на execCommand . Для того чтобы понять, поддерживает ли браузер то, что нам нужно, можно просто проверить наличие объекта clipboard в глобальном объекте navigator :
Итоги
Полагаем, унифицированный механизм работы с буфером обмена — это полезная возможность, поддержка которой в обозримом будущем появится во всех основных браузерах. Если данная тема вам интересна — взгляните на этот материал Джейсона Миллера.
Уважаемые читатели! Какие варианты использования API Clipboard кажутся вам самыми перспективными?
How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
Is there a way to copy (or cut) a file to the Windows clipboard from the command line?
In particular with a batch script. I know how to copy the contents to the clipboard ( type file | clip ), but this is not the case. I want to have the whole file as I would press Ctrl + C in Windows Explorer.
7 Answers 7
OK, it seems the easiest way was to create a small C# tool that takes arguments and stores them in the clipboard:
2017 edit: Here’s a github repo with both source and binary.
This would place the contents of the file into the clipboard (accomplished by clip.exe).
To get the actual file, you’ll probably have to resort to some other programming language, like VBScript or PowerShell to access Windows API’s. I’m not entirely certain what Explorer puts into the clipboard when you CTRL+C a file. I suspect it uses the notification system to do something more intelligent than put the path to the file there. Depending on the context of the CTRL+V, you’ll get something (Explorer, Word) or nothing (Notepad).
I’ve forever wanted this to use in Emacs, so, inspired by this question, an answer here, and a goodly amount of NIH syndrome, I’ve written a C version available at
picellif also handles wildcards (it’s not clear to me if rostok’s C# version does or not).
Windows script to copy some text to the clipboard?
I am using an application that requires several attempts to log in (because of overloaded servers).
This app has no «remember my password» feature.
Therefore, I would like to make a script (preferably a .bat script), that would first copy my password into the clipboard -so that I don’t have to retype my password on every log on attempt- , then launch the application (easy part)
Is this possible with a MS-DOS command ? Do I need a little exe or another script language ?
I’m obviously looking for the quickest solution to implement.
Thanks in advance for your ideas
5 Answers 5
http://www.petri.co.il/software/clip.zip
Note- Petri’s link is currently down. He got it from windows server 2003 but I see clip.exe on windows 7 too. It’s on windows versions post windows 7 too.
EDIT
The main thing is that clip command but as pointed out by Asu, a line like echo abc will also send a \r\n (which is a new line). If you want to avoid that, then that’s a very standard issue solved by replacing echo texttoecho , with echo|set/p=texttoecho So C:\>echo|set/p=texttoecho|clip
further addition
You can of course then paste with right click, but for a command line paste too.
unxutils(an ancient thing not maintained for well over a decade) has gclip and pclip (they don’t seem to be in gnuwin32), with those you can copy and paste via command line.
note- gnuwin32 might not be that updated either.
note- you can just copy all of wbin to e.g. c:\unxutils , and the EXEs have no dependencies/dlls.
and you can of course do pclip>a.a to paste to a file. or pclip|somecmd
barlop’s option isn’t entirely correct because echo will add a newline character to your password breaking it.
What you need to use instead is this:
This way the string will be copied to the clipboard as is.
I’ve myself encountered a similar scenario and here’s how I’ve solved it.
First, I store my passwords in the Windows Credential Vault (Windows Vista and greater). For this, I use Python’s keyring library, but you can just as well use something like CredMan (Powershell) to manage them. Using the Windows Credential Vault means the password never has to be typed on the command line, so is unlikely to leak (such as through a command-line history).
Second, I use a tool like clip to copy the password to the clipboard.
You may find you want to combine the two with your own PowerShell script that grabs the text from the credential manager and puts it on the clipboard. The script could be something as simple as:
Then, all you have to do is add the password to ‘Some System’ in Windows Credential Manager and that script will magically put the password on the clipboard on command.
AutoIt v3 can automate windows, which makes trying several login attempts easy.
AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying «runtimes» required!
AutoIt was initially designed for PC «roll out» situations to reliably automate and configure thousands of PCs. Over time it has become a powerful language that supports complex expressions, user functions, loops and everything else that veteran scripters would expect.
They have good examples, documentation and a solid community that can help you with script problems.
Although, you might be better off asking if they could solve the problem with their overloaded servers, as automating requests might only make the problem worse for them.
Copy text from a Windows CMD window to clipboard
Does anyone know if it’s possible to copy text from a Windows’ command prompt or console window like the output of a command, console application or batch file?
8 Answers 8
- Right click > Mark
- Select the text you want to copy by holding left mouse button and selecting text OR by navigating to the beginning of the text you want to copy with the arrow keys, pressing Shift, and moving (with the arrow keys) to the end of the text.
- right click on the title bar, go into «Edit», and hit Copy.
Now you can paste in Notepad or in Command Prompt again by right-clicking on the title bar, going into «Edit», and hitting «Paste.»
Another option, if you know ahead of time that you want the results of a command to be placed on the clipboard, is to pipe your output to the CLIP utility.
Here are a two simple examples
Open a command window, then right click on the title bar and left click on Properties at bottom of context menu. On the Options tab add a check-mark at QuickEdit Mode. Click OK and in the next dialog select the second radio button so that every command window that you will open in future has got this option enabled. Close the dialog with OK.
Now you can select text using left click on your mouse. To copy the text to the clipboard, just press the Enter key.
Follow these steps:
- Move pointer with pointing device (mouse, touchpad, pointing stick, . ) over the window, press right button to open the context menu and left click on first context menu option Mark.
- After that action select the text with holding left button (rectangular selection).
- After selecting hit key Enter or Return to copy selected text to clipboard.
- Paste copied text anywhere with Ctrl+V .