![](/img/trans.png)
[英]Secret copy to clipboard JavaScript function in Chrome and Firefox?
[英]Copy to clipboard pure javascript function in mozzila firefox
我需要制作一個在每個頁面和瀏覽器上都可以使用的按鈕,該按鈕可以從文本區域復制輸入。 我正在嘗試通過以下功能做到這一點:
selectElementContents: function(){
el = document.getElementById("tag_text");
var range = document.createRange();
range.selectNode(el);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
} catch(err) {
console.log('Oops, unable to copy');
}
目前,該功能在除Firefox和Safari之外的所有瀏覽器上均能正常運行。 我讀了一些有關Safari的信息,似乎它不支持這種功能,還是我弄錯了? 但是,當我嘗試使用document.execCommand('copy')復制輸入內容時,會引發以下錯誤: [Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: debugger eval code :: <TOP_LEVEL> :: line 1" data: no]
。 我查了一下這個錯誤,它是一種通用的,因為代碼包含了多個錯誤提示。
最后,我的問題是如何使它在firefox上運行,這是什么問題?
不幸的是,並非到處都支持execCommand('copy')。 它也不是很安全,因為它會將內容放入剪貼板而不會提醒用戶。
無論如何,您都可以將execCommand('copy')與此答案中針對不支持的瀏覽器提供的解決方案結合使用,例如:
HTML:
<form id="test_form">
<p>Copy this:</p>
<input id="tag_text" type="text" size="40" />
<input type="button" onClick="select_element_contents()" value="Copy" />
</form>
Javascript:
function select_element_contents (){
var el = document.getElementById("tag_text");
var el_text = el.value;
var range = document.createRange();
range.selectNode(el);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
} catch(err) {
window.prompt("Copy to clipboard: Ctrl+C/Cmd+C, Enter", el_text);
}
}
當然,這並不理想,但是由於Mozilla Firefox不支持自動復制到剪貼板,因此用戶必須按下按鈕。 最好使其盡可能透明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.