非SSLは今時珍しいけどね。
エラーになる
クリップボードに現在のurlを格納するために、こんな感じで作った。
$(function(){
const myUrl = $(location).attr('href');
$('button#btn_copy_url').on('click', function(){
navigator.clipboard.writeText(myUrl);
})
})ローカル環境だと動いたけど、非SSL(http://)だとエラーを吐いた。
Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')要するに無理だという話。
こんな感じ
別のアプローチになる。
$(function(){
const myUrl = $(location).attr('href');
$('button#btn_copy_url').on('click', function(){
const tempInput = $('<input>');
$('body').append(tempInput);
tempInput.val($(location).attr('href')).select();
const successful = document.execCommand('copy');
tempInput.remove();
if(!successful){
$span.html('コピー失敗');
}
})
})一旦inputに逃がしてそれを拾って「document.execCommand(‘copy’)」。
直接クリップボードに入れるんじゃなくて、言ってみればCtrl+Cを発火させてる感じですね。

コメント