如何知道javascript剪贴板"copy"事件的发起者
How to know the initiator of the javascript clipboard "copy" event
我已经在内容脚本中为剪贴板复制事件注册了一个侦听器,如下所示:
document.addEventListener("copy", function(event){
console.log("Copy event received");
});
我在以下情况下得到事件:
'Ctrl+C' 来自键盘。
'Copy' 从右键上下文菜单中选择。
'Copy' 从工具栏菜单中选择
在以上3种情况下,我都得到了“复制”事件,但我不知道复制是从哪里开始的。
有没有办法知道复制的来源?例如:'keyboard'、'context_menu'、'toolbar' ?
我想您需要监听器来监听您想要监视的事件。类似于:
let fromCtrlC = false;
let fromRightClick = false;
document.addEventListener( "copy", evt => {
console.clear();
const originatorEvent = fromCtrlC ? "CTRL-C" :
fromRightClick ? "right click" : "toolbar menu"
console.log(`Copy event received from ${originatorEvent} within element`,
evt.target);
fromCtrlC = false;
fromRightClick = false;
});
document.addEventListener( "keydown", evt =>
fromCtrlC = evt.key.toUpperCase() == 'C' && evt.ctrlKey );
document.addEventListener( "contextmenu", evt => fromRightClick = true );
<div id="hi">Hello</div>
<div id="world">world</div>
<div id="lorem">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
我已经在内容脚本中为剪贴板复制事件注册了一个侦听器,如下所示:
document.addEventListener("copy", function(event){
console.log("Copy event received");
});
我在以下情况下得到事件:
'Ctrl+C' 来自键盘。
'Copy' 从右键上下文菜单中选择。
'Copy' 从工具栏菜单中选择
在以上3种情况下,我都得到了“复制”事件,但我不知道复制是从哪里开始的。
有没有办法知道复制的来源?例如:'keyboard'、'context_menu'、'toolbar' ?
我想您需要监听器来监听您想要监视的事件。类似于:
let fromCtrlC = false;
let fromRightClick = false;
document.addEventListener( "copy", evt => {
console.clear();
const originatorEvent = fromCtrlC ? "CTRL-C" :
fromRightClick ? "right click" : "toolbar menu"
console.log(`Copy event received from ${originatorEvent} within element`,
evt.target);
fromCtrlC = false;
fromRightClick = false;
});
document.addEventListener( "keydown", evt =>
fromCtrlC = evt.key.toUpperCase() == 'C' && evt.ctrlKey );
document.addEventListener( "contextmenu", evt => fromRightClick = true );
<div id="hi">Hello</div>
<div id="world">world</div>
<div id="lorem">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>