This question is related to another question I asked, but I realized that a side-question in that question deserved its own question.
Using JavaScript, I'd like to see what users are copying from a webpage. Reading clipboard content is fairly easy when the user is pasting:
document.addEventListener("paste", e => {
let text = e.clipboardData.getData("text");
alert("pasting text: " + text);
});
This correctly creates an alert with whatever was just pasted. However, getting clipboard data is more difficult when the user is copying.
Method 1 (doesn't work)
document.addEventListener("copy", e => {
let text = e.clipboardData.getData("text");
alert("copying text: " + text);
});
This alerts "copying data: " but with no text after it. That's because the getData method is returning "" (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.
Method 2 (works, but with a popup)
document.addEventListener("copy", () => {
navigator.clipboard.readText().then(text => alert("copied text: " + text));
});
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.
Method 3 (seems to work, but doesn't seem right)
document.addEventListener("copy", () => {
let text = window.getSelection().toString();
alert("copying text: " + text);
});
This appears to do what I want. It seems odd that this would be allowed, but Method 1 would not.
I have a couple of questions:
- 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.
- Are there any cases where Method 3 would provide different results than Method 2 (in terms of the
textvariable, not popup behavior)? - Are there any other downsides to using Method 3 that I'm not considering?
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.