title: How to get copied text from JavaScript
body: <p>This question is related to <a href="https://stackoverflow.com/questions/52847316/get-permission-for-chrome-extension-to-read-copied-text">another question I asked</a>, but I realized that a side-question in that question deserved its own question.</p>
  
  <p>Using JavaScript, I'd like to see what users are copying from a webpage. Reading clipboard content is fairly easy when the user is <em>pasting</em>:</p>
  
  <pre><code>document.addEventListener("paste", e =&gt; {
    let text = e.clipboardData.getData("text");
    alert("pasting text: " + text);
  });
  </code></pre>
  
  <p>This correctly creates an alert with whatever was just pasted. However, getting clipboard data is more difficult when the user is <em>copying</em>.</p>
  
  <h2>Method 1 (doesn't work)</h2>
  
  <pre><code>document.addEventListener("copy", e =&gt; {
    let text = e.clipboardData.getData("text");
    alert("copying text: " + text);
  });
  </code></pre>
  
  <p>This alerts "copying data: " but with no text after it. That's because the <code>getData</code> method is returning <code>""</code> (the empty string). My understanding is that it would be considered too much of a security problem for sites to read your clipboard when you're doing anything other than pasting.</p>
  
  <h2>Method 2 (works, but with a popup)</h2>
  
  <pre><code>document.addEventListener("copy", () =&gt; {
    navigator.clipboard.readText().then(text =&gt; alert("copied text: " + text));
  });
  </code></pre>
  
  <p>This works, but before alerting, it creates a popup asking for permission for the site to read the clipboard. I would prefer to not have this popup.</p>
  
  <h2>Method 3 (seems to work, but doesn't seem right)</h2>
  
  <pre><code>document.addEventListener("copy", () =&gt; {
    let text = window.getSelection().toString();
    alert("copying text: " + text);
  });
  </code></pre>
  
  <p>This appears to do what I want. It seems odd that this would be allowed, but Method 1 would not.</p>
  
  <p>I have a couple of questions:</p>
  
  <ol>
  <li>Why is Method 1 not allowed, if Method 3 is? It seems like Method 1 could provide the same information as Method 3 does, and it would be more convenient and just as secure.</li>
  <li>Are there any cases where Method 3 would provide different results than Method 2 (in terms of the <code>text</code> variable, not popup behavior)?</li>
  <li>Are there any other downsides to using Method 3 that I'm not considering?</li>
  </ol>
  
  <p>At this point, I only care about these answers in the context of Google Chrome or Chromium, not other browsers. Answers to any of these questions would be appreciated.</p>