Get current clipboard content? [closed]

不问归期 提交于 2019-11-26 00:37:50

问题


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?


回答1:


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.




回答2:


Depending on when you read this, the new clipboard API may be available, via navigator.clipboard. It can be used like so:

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

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)

More on that

Spec




回答3:


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




回答4:


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.

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


来源:https://stackoverflow.com/questions/6413036/get-current-clipboard-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!