@Sahnen

Как по клику мышкой записать в буфер обмена значение?

Мне необходимо при клике по диву записывать в буфер генерируемый текст.
Вся беда в том, что по клику левой кнопкой мыши все работает как и задумывалось, а правой кнопкой - копирования не происходит (в консоль выводится false).

document.querySelector('#box').addEventListener('click', copyFunc);
document.querySelector('#box').addEventListener('contextmenu', function(e) {
    e.preventDefault();
    copyFunc(e);
});

function copyFunc(e) {
    var str = e.button === 0 ? 'Left click' : (e.button === 2 ? 'Right click' : 'Any text');
    var el = document.createElement('textarea');
    el.textContent = str;
    el.value = str;
    document.body.appendChild(el);

    var selection = document.getSelection();
    var range = document.createRange();
    range.selectNode(el);
    selection.removeAllRanges();
    selection.addRange(range);
    console.log(document.execCommand('copy'));
    selection.removeAllRanges();
    document.body.removeChild(el);
}


Нужно чтобы это работало в основных десктопных браузерах, хотя бы 2-летней давности.
Спасибо.
  • Вопрос задан
  • 126 просмотров
Решения вопроса 1
Vlad_IT
@Vlad_IT Куратор тега JavaScript
Front-end разработчик
https://w3c.github.io/editing/execCommand.html#dfn...
Copy commands triggered from document.execCommand() will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. How implementations can be configured to allow write access to the clipboard is outside the scope of this specification.


Короче говоря - click доверенное событие, а contextmenu - нет.
UPD: если использовать не onclick а mousedown (который срабатывает на все кнопки мыши) - то ок
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
jasonOk
@jasonOk
Легче болтать, чем код писать
Используйте https://clipboardjs.com/ и не морочьте голову
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы