-2

I wrote the following script, it works google chrome, but internet explorer does not work:

const readBtn = document.querySelector('.read-btn');
const writeBtn = document.querySelector('.write-btn');

const resultsEl = document.querySelector('.clipboard-results');
const inputEl = document.querySelector('.to-copy');

readBtn.addEventListener('click', () => {
  navigator.clipboard.readText()
    .then(text => {
      resultsEl.innerText = text;
    })
    .catch(err => {
      console.log('Something went wrong', err);
    })
});

writeBtn.addEventListener('click', () => {
  const inputValue = inputEl.value.trim();
  if (inputValue) {
    navigator.clipboard.writeText(inputValue)
      .then(() => {
        inputEl.value = '';
        if (writeBtn.innerText !== 'Copied!') {
          const originalText = writeBtn.innerText;
          writeBtn.innerText = 'Copied!';
          setTimeout(() => {
            writeBtn.innerText = originalText;
          }, 1500);
        }
      })
      .catch(err => {
        console.log('Something went wrong', err);
      })
  }
});
<div>
  <input type="text" class="to-copy" placeholder="Type something..." aria-label="Type something">
  <button class="write-btn">Сохранить ссылку в буфер обмена</button>
</div>

<div>
  <h3 class="clipboard-results"></h3>
  <button class="read-btn">Paste from clipboard</button>
</div>

Can you tell me the functions of writing to the clipboard on js that would work in ie?

1 Answers1

0

To copy to clipboard use exec command. It will work in IE larger than 8 and fully cross browser for modern browsers. unfortunately for pasting the only way is to use navigator.clipboard.readText() which is not supported for all browsers.

const readBtn = document.querySelector('.read-btn');
const writeBtn = document.querySelector('.write-btn');

const resultsEl = document.querySelector('.clipboard-results');
const inputEl = document.querySelector('.to-copy');

readBtn.addEventListener('click', () => {
  navigator.clipboard.readText()
    .then(text => {
      resultsEl.innerText = text;
    })
    .catch(err => {
      console.log('Something went wrong', err);
    })
});

writeBtn.addEventListener('click', () => {
  const inputValue = inputEl.value.trim();
  inputEl.select();
  document.execCommand("copy");
  alert('copied')
});

Js fiddle: https://jsfiddle.net/nd4Lfj7w/2/

Łukasz Blaszyński
  • 1,536
  • 1
  • 8
  • 13
  • To crossbrowser paste you can use "paste" event https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard but it is not reading from clipboard, you need to do paste action for some element, and then raed data and change etc before it is pasted. – Łukasz Blaszyński Nov 30 '18 at 08:25