Я пытаюсь написать простой скрипт, который позволяет пользователям копировать текущий URL страницы в буфер обмена.Моя проблема в том, что если любой другой текст копируется в буфер обмена, т.е. пользователь выделяет некоторый текст на странице с помощью Ctrl + C / Ctrl + V, исходный текст (URL страницы) исчезает / заменяется тем, что было скопировано последним.
Это мой код
HTML
<ul class="list-inline">
<li class="list-inline">....</li>
<li class="list-inline">....</li>
<li class="list-inline-item"><a class="btn btn-default" href="#" title="Copy link to Clipboard" id="copyURL"><i class="fas fa-link"></i> <span id="copyURLText">Copy URL</span></a></li>
</ul>
jQuery
$('#copyURL').click(function(event){
event.preventDefault();
//temporarily change text in link span
$('#copyURLText').text('Copied');
setTimeout(function(){
$('#copyURLText').text('Copy URL');
}, 1500);
//create text area and input value
var tempContainer = $('<textarea></textarea>');
tempContainer.val(window.location.href.replace(/\#/gi, ''));
//set attributes and position outside the screen
tempContainer.attr('readonly', true);
tempContainer.css({
'position': 'absolute',
'left': '-9999px',
'top': '0px'
})
//append to body
$('body').append(tempContainer);
//select element, copy text then remove
tempContainer.select();
document.execCommand('copy');
tempContainer.remove();
})
CSS
textarea{
display: none;
}