文档execCommand副本不使用AJAX

我不能直接复制生成的链接(没有ctrl + C)我是usign document.execCommand('copy')但它似乎没有效果。 如果代码没有AJAX那么它的工作就完美了 。 这是

  • 与AJAX的小提琴链接

  • 没有AJAX的小提琴链接

HTML

  

JQUERY

  $(".permalink-control") .append( '
' + ' ' + ' ' + '
' ); $(".permalink-control input") .hide() .focus(function () { // Workaround for broken selection: https://stackoverflow.com/questions/5797539 var $this = $(this); $this.select() .mouseup(function () { $this.unbind("mouseup"); return false; }); }); $(".permalink-control button") .click(function () { var $this = $(this); $.ajax({ url: "https://api-ssl.bitly.com/shorten", dataType: "jsonp", data: { longUrl: window.location.href, access_token: "48ecf90304d70f30729abe82dfea1dd8a11c4584", format: "json" }, success: function (response) { var longUrl = Object.keys(response.results)[0]; var shortUrl = response.results[longUrl].shortUrl; if (shortUrl.indexOf(":") === 4) { shortUrl = "https" + shortUrl.substring(4); } $this.parents(".permalink-control") .find("input") .show() .val(shortUrl) .focus(); }, async:false }); });

更新:

如何使用JavaScript复制到剪贴板?

我没有回答我的问题,因为我的代码也没有使用ctrl + C复制,如果AJAX不存在的话。 但是,当我使用AJAX document.execCommand('copy')不起作用时。

在W3规范中明确说明了这一点的原因:

通过脚本API触发的复制和剪切命令只会影响真实剪贴板的内容,前提是从用户信任和触发的事件调度事件,或者实现配置为允许此操作。

但是,我曾说过, when a user does some interaction ,我们可以通过复制文本来欺骗浏览器。

在这种情况下,由于您正在寻找click事件,我假设您的用户正在与mouse交互

那么,如果在解析ajax调用后附加$(window).blur()$(document).click()事件怎么办?

这是正确的,因为用户必须在某些时候blur以使用副本选择,用户将启动blur() or click() (depending on your need) ,我们可以将文本复制到剪贴板。

这是HACKY DEMO

 $(document).ready(function(){ var shortUrl; $(".permalink-control") .append( '
' + ' ' + ' ' + '
' ); $(".permalink-control input") .hide() .focus(function () { // Workaround for broken selection: http://stackoverflow.com/questions/5797539 var $this = $(this); $this.select(); document.execCommand('copy'); $this.mouseup(function () { $this.unbind("mouseup"); return false; }); }); $(".permalink-control button") .click(function () { var shortUrl =""; var $this = $(this); $.ajax({ url: "https://api-ssl.bitly.com/shorten", dataType: "jsonp", data: { longUrl: window.location.href, access_token: "48ecf90304d70f30729abe82dfea1dd8a11c4584", format: "json" }, success: function (response) { var longUrl = Object.keys(response.results)[0]; shortUrl = response.results[longUrl].shortUrl; if (shortUrl.indexOf(":") === 4) { shortUrl = "https" + shortUrl.substring(4); } $this.parents(".permalink-control") .find("input") .show() .val(shortUrl) .focus(); } }).done(function(){ $(window).blur(function(){ document.execCommand('copy'); $(window).off('blur');// make sure we don't copy anything else from the document when window is foucussed out }); }) }); })