Search code examples
javascriptclipboardclipboarddata

How to know the initiator of the javascript clipboard "copy" event


I've registered a listener for the Clipboard copy event in the content script as follows:

document.addEventListener("copy", function(event){
    console.log("Copy event received");
});

I get the event in the following cases:

  1. 'Ctrl+C' from keyboard.

  2. 'Copy' selected from the right click context menu.

  3. 'Copy' selected from the toolbar menu

    Toolbar copy

In all the above 3 cases, I get the "copy" event but I do not know from where the copy was initiated.

Is there a way to know the source from where the copy was initiated ? Eg: 'keyboard', 'context_menu', 'toolbar' ?


Solution

  • I suppose you need listeners for the events you want to monitor. Something like:

    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>