R
R
Roman Tatarinov2018-07-04 16:49:02
JavaScript
Roman Tatarinov, 2018-07-04 16:49:02

How to solve execComand('copy') problem on IOS?

The essence of the problem: when you click on a button on the site, some information that is located somewhere on the site should be copied, in my case in `data-attr`. Copying everywhere except `IOS` can be easily done with `execCommand('copy')`. That is, we create some kind of hidden `input` or `textarea`, execute `select()` in it, and then `execCommand('copy')`. With IOS, everything is not obvious. Stackoverflow offers a solution via userAgent

const iosFlag = !!navigator.userAgent.match(/ipad|ipod|iphone/i);

const copyClipBoard() {
    if (iosFlag) {
      const oldContentEditable = this.textArea.contentEditable;
      const oldReadOnly = this.textArea.readOnly;
      const range = document.createRange();

      this.textArea.contenteditable = true;
      this.textArea.readonly = false;
      range.selectNodeContents(this.textArea);

      const s = window.getSelection();

      s.removeAllRanges();
      s.addRange(range);

      this.textArea.setSelectionRange(0, 999999);
      this.textArea.contentEditable = oldContentEditable;
      this.textArea.readOnly = oldReadOnly;

      document.execCommand('copy');
    }
  }


The solution is working, but the problem is that on IOS the page scrolls to the place where the input was created. THAT is if I do `document.body.appendChild(myTetxtArea)` it will scroll straight to that element. You can solve the problem by creating a `textarea` right below the copy button. Then the scroll is minimal (but it is), while the keyboard of the device appears for a fraction of a second and disappears.

And, in fact, I do not know how to solve the problem of the appearance of the keyboard and microscroll? Are there any other solutions to copy by button, while on IOS it was as visual as everywhere else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jasonOk, 2018-07-04
@jasonOk

Use https://github.com/zenorocha/clipboard.js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question