chrome 扩展程序访问剪贴板操作总结
微wx笑
2025-05-11【前端开发】
10
0
0关键字:
chrome 扩展程序 剪贴板
chrome 扩展程序访问剪贴板操作总结读取剪贴板中的内容:// 创建临时 textarea 用于粘贴const textarea = document.createElement('textarea');textarea.style.posit
chrome 扩展程序访问剪贴板操作总结
读取剪贴板中的内容:
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); |
这种老的方式虽然使用的代码比较多,但是不会弹出提示;
下面这种新的方式就会弹出提示,询问用户是否允许,如果用户不允许,那么就访问失败了;
1 2 3 | // 尝试读取剪贴板 //const text = await navigator.clipboard.readText(); //console.log(`await剪贴板内容: ${text}`); |
写入剪贴板是使用这样的方式:
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 事件
而下面这种新的方式却不会,也不会弹出询问用户是否允许的对话框
浏览器的安全策略更多限制的是读取,
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 的方式,但是需要是用户主动交互的,比如单击按钮
像用户按下Ctrl+C这样的快捷键是不行的;
1 | var cData = e.clipboardData || window.clipboardData; |
本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2025-05-11/2070.html
下一篇:返回列表