您可以尝试以下代码,它将文本写入剪贴板
作为一个例子,我写到Sample
剪贴板
输出
清单.json
清单文件是所有 chrome 扩展的关键,确保它具有所有权限
{
"name": "Copy to ClipBoard Demo",
"description" : "This is used for demonstrating Copy to Clip Board Functionality",
"version": "1",
"browser_action": {
"default_popup": "popup.html"
},
"permissions":["clipboardWrite"],
"manifest_version": 2
}
popup.html
一个简单的浏览器操作 HTML 文件,带有输入框和按钮
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<input type="text" id="text" placeHolder="Enter Text To Copy"></input>
<button id="copy">Copy</button>
</body>
</html>
popup.js
它将内容复制<input>
到剪贴板
function copy() {
//Get Input Element
var copyDiv = document.getElementById('text');
//Give the text element focus
copyDiv.focus();
//Select all content
document.execCommand('SelectAll');
//Copy Content
document.execCommand("Copy", false, null);
}
//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("copy").onclick = copy;
});
或者
function copy(){
//Get Input Element
document.getElementById("text").select();
//Copy Content
document.execCommand("Copy", false, null);
}
//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("copy").onclick = copy;
});