Скопируйте HTML в буфер обмена IE11 - PullRequest
0 голосов
/ 01 октября 2019

Если пользователи выбирают и копируют html с моего сайта, я хочу добавить токен доступа к изображениям. Этот код отлично работает в Chrome / Firefox / Edge. В IE11 я не могу установить "text / html" на window.clipboardData.setData. Есть ли другой способ решить эту задачу?

//Polyfill for ParentNode.append in IE11
(function (arr) {
  arr.forEach(function (item) {
    if (item.hasOwnProperty('append')) {
      return;
    }
    Object.defineProperty(item, 'append', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function append() {
        var argArr = Array.prototype.slice.call(arguments),
          docFrag = document.createDocumentFragment();
        
        argArr.forEach(function (argItem) {
          var isNode = argItem instanceof Node;
          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
        });
        
        this.appendChild(docFrag);
      }
    });
  });
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);

function getSelectedRange() {
    var range = window.getSelection().getRangeAt(0);
    var el = document.createElement("div");
    el.append(range.cloneContents());
    return el;
}

function onCopyHandler(e) {
    var range = getSelectedRange();
    var images = range.getElementsByTagName("img");

    for (var i = 0; i < images.length; i++) {
        images[i].src = images[i].src + "?token=ABCD";
    }

    var html = range.innerHTML;
    if (e.clipboardData) { // not available in IE11
        e.clipboardData.setData("text/html", html);
    }
    else {
        try {
            window.clipboardData.setData("Text", html); // can't write text/html
        }
        catch (e) {}
    }
    e.preventDefault();
}

document.addEventListener("copy", onCopyHandler);
<p>Select text img text and CTRL+C -> access token should be added to img url</p>

Text
<img src="https://cdn.sstatic.net/img/progress-dots.gif" alt="">
Text
...