[英]execCommand not working in javascript jQuery to copy text to clipboard
[英]Using execCommand (Javascript) to copy hidden text to clipboard
我正在嘗試在不使用 Flash 的情況下復制到剪貼板,如果瀏覽器與 javascript 方法不兼容,我計划使用ZeroClipboard回退到 Flash。
我有一個按鈕的 onClick 偵聽器,如下所示:
$(buttonWhereActionWillBeTriggered).click(function(){
var copyDiv = document.getElementById(inputContainingTextToBeCopied);
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
}
和一個輸入字段如下:
<input type="text" name="Element To Be Copied" id="inputContainingTextToBeCopied" value="foo"/>
這目前按預期工作,但設計要求包含要復制的文本的字段不可見。 我已經嘗試過設置type="hidden"
和style="display: none"
都沒有成功。 兩者都會導致按鈕選擇整個頁面並將整個內容復制到用戶的剪貼板。
我相對相信原因不是基於瀏覽器,但為了以防萬一,我正在 Mac OS X 10.10.4 上的 Chrome(版本 43.0.2357.134(64 位))上進行測試。
有沒有辦法可以在隱藏 <input> 的同時保持其可見的功能? 或者如果不是我可以采取的替代路線?
我知道類似的問題,沒有一個能解決我的問題,要么是太老了,要么是沒有實際使用 Javascript,要么是不適合特定場景。 對於任何有類似的、不太具體的問題的人來說,這是一個很好的答案。
這是我不使用 jQuery 的解決方案:
function setClipboard(value) { var tempInput = document.createElement("input"); tempInput.style = "position: absolute; left: -1000px; top: -1000px"; tempInput.value = value; document.body.appendChild(tempInput); tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); }
<!DOCTYPE html> <html> <head> <title>Set Clipboard</title> </head> <body> <button onclick="setClipboard('foo loves bar')">Set Clipboard</button> </body> </html>
2019 - 仍在尋找沒有屏幕外內容的答案。
我所做的是首先將輸入文本字段更改為 type="text",復制文本,然后將其改回 type="hidden"。 這很好用。
<input id="dummy" name="dummy" type="hidden">
<script>
var copyText = document.getElementById("dummy");
copyText.type = 'text';
copyText.select();
document.execCommand("copy");
copyText.type = 'hidden';
</script>
[1] 在 Firefox 41 之前,需要在 user.js 首選項文件中啟用剪貼板功能。 有關詳細信息,請參閱Mozilla 首選項簡要指南。 如果該命令不受支持或啟用,則 execCommand 會引發異常而不是返回 false。 在 Firefox 41 及更高版本中,默認情況下在任何能夠彈出窗口的事件處理程序中啟用剪貼板功能(半可信腳本)。
由於Firefox 版本 41 Document.execCommand() 現在可以工作。 所以不需要再使用回退了。
由於瀏覽器在訪問剪貼板時的行為似乎有所不同,因此我花了一些時間來理解它。
它與您的解決方案非常相似,但不同之處在於創建一個臨時元素並用輸入value
填充它。 這樣我們就可以將輸入的display
屬性設置為none
。
IE也有一個使用window.clipboardData
的解決方法。
Firefox根本不允許我訪問剪貼板。 所以我不得不添加一個prompt
,讓用戶手動復制輸入值。 當然, prompt
很丑,但您可以只使用像窗口這樣的模式,也可以這樣做。
由於這似乎是一件棘手的事情,因此我在Win7(64 位)上進行了測試
鉻 - 版本 43.0.2357.134 m
IE - 版本 11.0.9600.17914
和 Firefox 無關緊要,因為它無論如何都不會讓我訪問它。
var copyBtn = $("#copy-btn"), input = $("#copy-me"); function copyToClipboardFF(text) { window.prompt ("Copy to clipboard: Ctrl C, Enter", text); } function copyToClipboard() { var success = true, range = document.createRange(), selection; // For IE. if (window.clipboardData) { window.clipboardData.setData("Text", input.val()); } else { // Create a temporary element off screen. var tmpElem = $('<div>'); tmpElem.css({ position: "absolute", left: "-1000px", top: "-1000px", }); // Add the input value to the temp element. tmpElem.text(input.val()); $("body").append(tmpElem); // Select temp element. range.selectNodeContents(tmpElem.get(0)); selection = window.getSelection (); selection.removeAllRanges (); selection.addRange (range); // Lets copy. try { success = document.execCommand ("copy", false, null); } catch (e) { copyToClipboardFF(input.val()); } if (success) { alert ("The text is on the clipboard, try to paste it!"); // remove temp element. tmpElem.remove(); } } } copyBtn.on('click', copyToClipboard);
#copy-me { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="Element To Be Copied" id="copy-me" value="foo loves bar"/> <button id="copy-btn">Copy</button><br/><br/> <textarea placeholder="paste here"></textarea>
感謝@DavidDomain 的幫助,我發現了一種有點笨拙但實用的方法。
首先,我將輸入方式移出屏幕並修改了一些屬性,結果如下:
<input type="text" name="Element To Be Copied" id="inputContainingTextToBeCopied" value="foo" style="display:none; position: relative; left: -10000px;"/>
display:none 是在對js進行以下修改后添加的
之后,@Pokkanome 的評論讓我可以像這樣修改 onClick 函數:
$(buttonWhereActionWillBeTriggered).click(function(){
var copyDiv = document.getElementById(inputContainingTextToBeCopied);
copyDiv.style.display = 'block';
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
copyDiv.style.display = 'none';
}
我不確定是否可以使用這種方法從隱藏的 div 中復制,這在瀏覽器安全性方面是有意義的,因為毫無疑問地訪問剪貼板會有一些風險。 不過,所采取的方法具有相同的預期結果。
我這里有一個不太過時的解決方案:
使用此腳本,您可以復制數據。 它比過去提供的腳本小得多。
該腳本的作用是使用一個隱藏在屏幕側面的輸入,通過 CSS 或內聯樣式,然后快速選擇它並運行復制命令。
function copyFunc() { var copyText = document.getElementById("copyInp"); copyText.select(); document.execCommand("copy"); //this function copies the text of the input with ID "copyInp" }
<input type="text" value="StuffYaWantCopied" id="copyInp" style="position:absolute;left:-1000px;top:-1000px;"> <a onclick="copyFunc()" style="cursor:cell;"> Click here to Copy! </a>
對於獎勵,我制作了一個小的剪貼板 API,它可以使用 Contenteditable Divs 和動態變量動態選擇元素並從中檢索文本: https ://codepen.io/SkylerSpark/pen/OJJqxWX
此外,請參閱下面的 Ciprians Answer,了解使用新的 Permissions API 將文本直接發送到用戶允許的權限的剪貼板,它不完全受支持,但它在最新的瀏覽器中可用(我知道它現在實際上適用於 chrome,但我還沒有測試過任何其他瀏覽器): https : //stackoverflow.com/a/58099014/11165703
您可以簡單地使用 opacity:0.00000000000001 隱藏輸入標簽,然后使用 javascript 將隱藏文本復制到剪貼板
function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); copyText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Text copied successfully"); }
<input type="text" value="===your text here===" id="myInput" style="opacity:0.00000000000001"> <button onclick="myFunction()">Copy</button>
適用於所有瀏覽器的替代解決方法是,您可以將其不透明度設置為具有絕對位置的 0,而不是隱藏元素。
#copy-me {
position: absolute;
opacity: 0;
}
對我有用的是:
<div>
<a class="copyBtn">Copy</a>
<input class="d-none" value="teste">
</div>
和:
$('.copyBtn').on('click', function(e) {
e.preventDefault();
var input = $(this).parent().find(".dirVal");
$(input).removeClass("d-none");
input.select();
document.execCommand('copy');
$(input).addClass("d-none");
callNotify("Parabéns!", "Caminho copiado para área de transferência!", "success");
});
您可以為此使用window.navigator
:
navigator.clipboard.writeText('this will be copied to the clipboard');
使用這個怎么樣: https : //developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
navigator.clipboard.writeText("<empty clipboard>").then(function() {
/* clipboard successfully set */
}, function() {
/* clipboard write failed */
});
去做就對了!
.blind {
overflow: hidden;
position: absolute;
clip: rect(0 0 0 0);
width: 1px;
height: 1px;
margin: -1px;
}
<textarea id="copy" class="blind">
your copy text here!
</textarea>
copyClipboard(document.getElementById('copy'));
function copyClipboard(el) {
el.select();
window.document.execCommand('copy');
}
https://gist.github.com/seunggabi/7ae53c100d647cb19c48047cff9b7019
對我有用的兩種方法:
方法1:在這種方法中,輸入元素最初是隱藏的,復制功能取消隱藏它,選擇並復制文本,然后再次隱藏它。
<script>
function copyLinkToClipboardViaHiddenField() {
el = document.querySelector("#input");
el.style.display = "block";
var copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
el.style.display = "none";
document.getElementById("copylink").innerText = "copied OK!";
document.getElementById("copylink").href = "";
document.getElementById("copylink").style.color = "black";
document.getElementById("copylink").style.textDecoration = "none";
return false; // prevents click doing anything
}
</script>
<input id="input"
type="text"
style="display: none;"
value="https://www.example.org/ViaHiddenField"/>
<a href="javascript:void(0)"
onclick="return copyLinkToClipboardViaHiddenField()"
id="copylink"
style="text-decoration: underline;color: blue;">copy link ViaHiddenField</a>
方法2:在這種方法中,創建一個新的輸入元素並將其附加到文檔正文的底部,復制其值,然后刪除該元素。
<script>
function copyLinkToClipboardViaAppendElement() {
el = document.createElement("input");
el.setAttribute('type', 'text');
el.setAttribute('value', "https://www.example.org/ViaAppendElement");
document.body.appendChild(el)
el.select();
console.log(el)
document.execCommand("copy");
el.parentNode.removeChild(el);
document.getElementById("copylink").innerText = "copied OK!";
document.getElementById("copylink").href = "";
document.getElementById("copylink").style.color = "black";
document.getElementById("copylink").style.textDecoration = "none";
return false; // prevents click doing anything;
}
</script>
<a href="javascript:void(0)"
onclick="return copyLinkToClipboardViaAppendElement()"
id="copylink"
style="text-decoration: underline;color: blue;">copy link ViaAppendElement</a>
要將文本復制到剪貼板,它必須是可見的。 所以我創建了一個 input type=text 但設置了 style display:none 並使用 jquery 在復制周圍執行 show() 和 hide() 。
<input type=text id='me' value='bla' style='display:none;'>
<button onclick='
$("#me").show();
var copyText = document.getElementById("me");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
$("#me").hide();
alert("Link copied to clipboard");
'></button>
這是一個簡單的,但似乎對我有用的答案。 而不是使用display: none;
用這個:
height: 0px; width: 0px; overflow: hidden; position: absolute;
這允許在仍然隱藏文本區域而不影響設計的同時進行選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.