如何在 Chrome 和 Firefox 中秘密地將 JavaScript 函式複製到剪貼簿?


在本文中,我們將嘗試如何秘密地將 JavaScript 函式複製到剪貼簿。

我們使用 copytext() 方法將 JavaScript 函式秘密複製到剪貼簿。這些函式也適用於 JavaScript 控制檯。要更好地理解,讓我們逐一檢視示例。

示例

以下是我們使用 copyText() 方法透過 JavaScript 函式將文字複製到剪貼簿的示例程式。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); // alert("Copied the text: " + copyText.value); } </script> </body> </html>

新增警報

我們還可以在 copytext() 方法複製的文字中,使用 alert() 方法新增警報。

示例

以下是將文字複製到剪貼簿的示例程式,並且在複製文字後將顯示警報。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } </script> </body> </html>

複製文字的警報內容為 -

示例

以下是使用 copyClipboard() 函式將文字複製到剪貼簿的示例程式 -

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Text" id="input"> <button onclick="copyClipboard()">Copy text Here!</button> <script> function copyClipboard() { var sampleText = document.getElementById("input"); sampleText.select(); sampleText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Copied the text: " + sampleText.value); document.write("Copied Text here:", sampleText.value); } </script> </body> </html>

更新於: 18-11-2022

982 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告