Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript复制到剪贴板?(How do I copy to the clipboard in JavaScript?)

What is the best way to copy text to the clipboard?

(将文本复制到剪贴板的最佳方法是什么?)

(multi-browser)

((多浏览器))

I have tried:

(我试过了:)

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else {  
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
        const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);  
        clipboardHelper.copyString(text);
    }
}

but in Internet Explorer it gives a syntax error.

(但是在Internet Explorer中,它会给出语法错误。)

In Firefox, it says unsafeWindow is not defined .

(在Firefox中,它说unsafeWindow is not defined 。)

A nice trick without flash: How does Trello access the user's clipboard?

(一个没有闪光灯的好技巧: Trello如何访问用户的剪贴板?)

  ask by Santiago Corredoira translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Overview(总览)

There are three primary browser APIs for copying to the clipboard:

(有三种主要的浏览器API可复制到剪贴板:)

  1. Async Clipboard API [navigator.clipboard.writeText]

    (异步剪贴板API [navigator.clipboard.writeText])

    • Text-focused portion available in Chrome 66 (March 2018)

      (Chrome 66中提供了以文本为中心的部分(2018年3月))

    • Access is asynchronous and uses JavaScript Promises , can be written so security user prompts (if displayed) don't interrupt the JavaScript in page.

      (访问是异步的,并且使用JavaScript Promises ,可以编写,因此安全用户提示(如果显示)不会中断页面??中的JavaScript。)

    • Text can be copied to the clipboard directly from a variable.

      (文本可以直接从变量复制到剪贴板。)

    • Only supported on pages served over HTTPS.

      (仅在通过HTTPS服务的页面上受支持。)

    • In Chrome 66 pages in active tabs can write to the clipboard without a permissions prompt.

      (在Chrome 66中,活动标签页中的页面可以写入剪贴板而没有权限提示。)

  2. document.execCommand('copy')
    • Most browsers support this as of ~April 2015 (see Browser Support below).

      (截至2015年4月,大多数浏览器都支持此功能(请参阅下面的浏览器支持)。)

    • Access is synchronous, ie stops JavaScript in the page until complete including displaying and user interacting with any security prompts.

      (访问是同步的,即在页面中停止JavaScript直到完成,包括显示和用户与任何安全提示进行交互。)

    • Text is read from the DOM and placed on the clipboard.

      (从DOM中读取文本并将其放置在剪贴板上。)

    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.

      (在2015年4月?测试期间,只有Internet Explorer被记录为在写入剪贴板时显示权限提示。)

  3. Overriding the copy event

    (覆盖复制事件)

    • See Clipboard API documentation on Overriding the copy event .

      (请参阅剪贴板API文档中有关覆盖复制事件的信息 。)

    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.

      (允许您通过任何复制事件来修改剪贴板上显示的内容,可以包括除纯文本之外的其他数据格式。)

    • Not covered here as it doesn't directly answer the question.

      (此处未涵盖,因为它不能直接回答问题。)

General development notes(一般发展说明)

Don't expect clipboard related commands to work whilst you are testing code in the console.

(在控制台中测试代码时,不要期望剪贴板相关的命令能够正常工作。)

Generally the page is required to be active (Async Clipboard API) or requires user interaction (eg a user click) to allow ( document.execCommand('copy') ) to access the clipboard see below for more detail.

(通常,页面需要处于活动状态(异步剪贴板API)或需要用户交互(例如,用户单击)才能允许( document.execCommand('copy') )访问剪贴板,有关更多详细信息,请参见下文。)

Async + Fallback(异步+后备)

Due to the level of browser support for the new Async Clipboard API you will likely want to fallback to the document.execCommand('copy') method to get good browser coverage.

(由于浏览器对新的Async Clipboard API的支持水平,您可能希望回退到document.execCommand('copy')方法以获得良好的浏览器覆盖率。)

Here is a simple example:

(这是一个简单的示例:)

 function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position="fixed"; //avoid scrolling to bottom document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); } catch (err) { console.error('Fallback: Oops, unable to copy', err); } document.body.removeChild(textArea); } function copyTextToClipboard(text) { if (!navigator.clipboard) { fallbackCopyTextToClipboard(text); return; } navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); }); } var copyBobBtn = document.querySelector('.js-copy-bob-btn'), copyJaneBtn = document.querySelector('.js-copy-jane-btn'); copyBobBtn.addEventListener('click', function(event) { copyTextToClipboard('Bob'); }); copyJaneBtn.addEventListener('click', function(event) { copyTextToClipboard('Jane'); }); 
 <div style="display:inline-block; vertical-align:top;"> <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br /> <button class="js-copy-jane-btn">Set clipboard to JANE</button> </div> <div style="display:inline-block;"> <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard: </textarea> </div> 

Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011

(请注意,此代码段在Stack Overflow的嵌入式预览中效果不佳,您可以在这里尝试: https : //codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011)

Async Clipboard API(异步剪贴板API)

Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.

(请注意,可以通过Chrome 66中的权限API来“请求权限”并测试对剪贴板的访问权限。)

var text = "Example text to appear on clipboard";
navigator.clipboard.writeText(text).then(function() {
  console.log('Async: Copying to clipboard was successful!');
}, function(err) {
  console.error('Async: Could not copy text: ', err);
});

document.execCommand('copy')(document.execCommand('copy'))

The rest of this post goes into the nuances and detail of the document.execCommand('copy') API.

(本文的其余部分深入介绍document.execCommand('copy') API的细微差别和细节。)

Browser Support(浏览器支持)

The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates:

(对JavaScript document.execCommand('copy')支持已经增长,请参阅下面的链接以获取浏览器更新:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...