文档execCommand副本不能与AJAX一起使用

问题描述 投票:4回答:2

我不能直接复制生成的链接(没有ctrl + C)我正在使用qazxsw poo但它似乎没有效果。如果代码没有AJAX,那么它的工作正常。这是

HTML:

fiddle link without AJAX

JQUERY:

<div class="permalink-control"> </div>

更新:

$(".permalink-control") .append( '<div class="input-group">' + ' <span class="input-group-btn"><button type="button" class="btn btn-default" title="Get Permalink"><span class="glyphicon glyphicon-link"></span></button></span>' + ' <input type="text" class="form-control">' + '</div>' ); $(".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: "your access token", 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 }); });

没有回答我的问题,因为如果没有AJAX,我的代码也会在没有使用ctrl + C的情况下进行复制。但是,当我使用AJAX时,How do I copy to the clipboard in JavaScript?无效。

javascript jquery ajax
2个回答
5
投票

document.execCommand('copy')明确说明了这一点的原因:

如果从用户信任和触发的事件调度事件,或者实现配置为允许此操作,则通过脚本API触发的复制和剪切命令将仅影响实际剪贴板的内容。

但是,说过我们可以尝试通过复制文本W3 specs来欺骗浏览器。

在这种情况下,因为你正在寻找一个when a user does some interaction事件我假设你是用户正在与click进行交互

那么,如果我在ajax调用解决后附加了mouse$(window).blur()事件怎么办?

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

这是blur() or click() (depending on your need)

HACKY DEMO
$(document).ready(function(){
    var shortUrl;
    $(".permalink-control")
      .append(
        '<div class="input-group">' +
        '    <span class="input-group-btn"><button type="button" class="btn btn-default" title="Get Permalink"><span class="glyphicon glyphicon-link"></span></button></span>' +
        '    <input type="text" class="form-control">' +
        '</div>'
      );
     $(".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
            });
       })
    });
})

P.S:这已经过镀铬测试。


2
投票

我有同样的问题。我原来解决了这个问题:在click事件的处理程序中,你可以运行一个间隔来检查ajax在服务器响应后插入值的变量。收到答案后,我们停止间隔并开始使用剪贴板。没问题,因为用户自己在点击后开始间隔,没有任何回调。

简单的jQuery示例:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="permalink-control"></div> 
<div class"log"></div>

在此示例中,当单击按钮时,我们将一些数据发送到服务器并通过检查var ajaxResponse; function copyText(copiedText){ $('<textarea class="copied-text">' + copiedText + '</textarea>').appendTo('body'); if ( navigator.userAgent.match(/ipad|iphone/i) ) { var range = document.createRange(), textArea = $('.copied-text')[0]; range.selectNodeContents(textArea); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); textArea.setSelectionRange(0, 999999); } else { $('.copied-text').select(); } document.execCommand('copy'); $('.copied-text').remove(); }; function myAjaxFunc(){ $.ajax({ type: 'POST', url: yourUrl, data: yourData, success: function(data){ ajaxResponse = data; } }); }; $('.your-button').on('click', function(){ myAjaxFunc(); var ajaxCheckTimer = setInterval(function(){ if ( ajaxResponse ) { copyText(ajaxResponse); clearInterval(ajaxCheckTimer); }; }, 100); }); 变量的值来启动间隔。

收到服务器的响应后,服务器的响应将写入此变量,之后间隔中的条件变为true,并调用文本复制函数,并将服务器响应变量指定为参数:ajaxResponse。间隔停止。

copyText(ajaxResponse);函数在页面上使用copyText变量的值创建textarea,将该值从字段复制到剪贴板,并从页面中删除该字段。

更新01.07.19

要在iOS上正确复制到剪贴板,请将值为ajaxResponse的属性contenteditable添加到文本字段:

true
© www.soinside.com 2019 - 2024. All rights reserved.