Javascript 获取当前剪贴板内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6413036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current clipboard content?
提问by Gabriele Cirulli
I'd like to know a way to make my script detect the content of the clipboard and paste it into a text field when the page is opened, with no input from the user. How can it be done?
我想知道一种方法,让我的脚本检测剪贴板的内容,并在页面打开时将其粘贴到文本字段中,而无需用户输入。怎么做到呢?
回答by Dave
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
window.clipboardData.getData('Text')
将在某些浏览器中工作。然而,它工作的许多浏览器会提示用户他们是否希望网页可以访问剪贴板。
回答by iuliu.net
Use the new clipboard API, via navigator.clipboard
. It can be used like this:
使用新的剪贴板 API,通过navigator.clipboard
. 它可以像这样使用:
navigator.clipboard.readText()
.then(text => {
console.log('Pasted content: ', text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
Or with async syntax:
或者使用异步语法:
const text = await navigator.clipboard.readText();
const text = await navigator.clipboard.readText();
Keep in mind that this will prompt the user with a permission request dialog box, so no funny business possible.
请记住,这将提示用户一个权限请求对话框,所以不可能有任何有趣的事情。
(NOTE: This will not work if called from the console, but will require a direct user action such as pressing a button, thanks @Artur)
(注意:如果从控制台调用这将不起作用,但需要直接的用户操作,例如按下按钮,谢谢@Artur)
回答by Ricky Jiao
You can use
您可以使用
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
在 IE 中获取用户剪贴板的内容。但是,在其他浏览器中,您可能需要使用 flash 来获取内容,因为没有访问剪贴板的标准界面。也许你可以试试这个插件零剪贴板
回答by Sollymanul Islam
Following will give you the selected content as well as updating the clipboard.
以下将为您提供所选内容以及更新剪贴板。
Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.
将元素 id 与 copy 事件绑定,然后获取选定的文本。您可以替换或修改文本。获取剪贴板并设置新文本。要获得确切的格式,您需要将类型设置为“text/hmtl”。您也可以将它绑定到文档而不是元素。
$(ElementId).bind('copy', function(event) {
var selectedText = window.getSelection().toString();
selectedText = selectedText.replace(/\u200B/g, "");
clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
clipboardData.setData('text/html', selectedText);
event.preventDefault();
});