前端开发您现在的位置是:首页 > 博客日志 > 前端开发

chrome 扩展程序访问剪贴板操作总结

<a href='mailto:'>微wx笑</a>的头像微wx笑 2025-05-11前端开发10 0 0关键字: chrome 扩展程序  剪贴板  

chrome 扩展程序访问剪贴板操作总结读取剪贴板中的内容:// 创建临时 textarea 用于粘贴const textarea = document.createElement(&#39;textarea&#39;);textarea.style.posit

无知人生,ivu4e.com,ivu4e.cn

chrome 扩展程序访问剪贴板操作总结uae无知

读取剪贴板中的内容:uae无知

1
2
3
4
5
6
7
8
9
10
11
12
13
// 创建临时 textarea 用于粘贴
const textarea = document.createElement('textarea');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
 
// 执行粘贴命令
document.execCommand('paste');
var text = textarea.value;
document.body.removeChild(textarea);
 
console.log('aaa剪贴板内容:', text);

这种老的方式虽然使用的代码比较多,但是不会弹出提示;uae无知

下面这种新的方式就会弹出提示,询问用户是否允许,如果用户不允许,那么就访问失败了;uae无知

1
2
3
// 尝试读取剪贴板
//const text = await navigator.clipboard.readText();
//console.log(`await剪贴板内容: ${text}`);

写入剪贴板是使用这样的方式:uae无知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var conEle = document.createElement("input");
if (str.includes('\n') || str.includes('\r')){
    conEle = document.createElement("textarea");
}
var selectionObj = window.getSelection();
var rangeObj = null;
if (selectionObj.rangeCount > 0){
    rangeObj = selectionObj.getRangeAt(0);
}
conEle.value = str; //str.replace(/[\r\n]/g, '');
conEle.style.position = 'fixed';
conEle.style.left = '-9999px';
document.body.appendChild(conEle);
conEle.select();
document.execCommand("copy");
conEle.remove();

但是这种老的方式会再次触发 copy 事件uae无知

而下面这种新的方式却不会,也不会弹出询问用户是否允许的对话框uae无知

浏览器的安全策略更多限制的是读取,uae无知

1
2
3
4
5
6
7
8
9
var mkdown = selection.html.replace(/<\/?strong>/g, '**');
const clipboardItem = new ClipboardItem({
    'text/html'new Blob([mkdown], { type: 'text/html' }),
    'text/plain'new Blob([mkdown], { type: 'text/plain' })
});
 
// 写入剪贴板
await navigator.clipboard.write([clipboardItem]);
console.log('成功写入剪贴板', selection.html);

有一种通过 clipboardData  的方式,但是需要是用户主动交互的,比如单击按钮uae无知

像用户按下Ctrl+C这样的快捷键是不行的;uae无知

1
var cData = e.clipboardData || window.clipboardData;


uae无知

无知人生,ivu4e.com,ivu4e.cn

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2025-05-11/2070.html

很赞哦! (4) 有话说 (0)

文章评论