Get permission for Chrome extension to read copied

2019-07-06 17:52发布

问题:

I'm creating a Chrome extension. I'd like to be able to see what users are copying to their clipboard from Chrome. Here's what I have currently working, in a content script:

document.addEventListener(
    "copy",
    () => navigator.clipboard.readText().then(
        text => console.log("copied text: " + text)
    )
);

For security reasons that make sense, Chrome doesn't allow you to get the clipboard from the copy event itself. Instead, I have to get it from the navigator. The only issue is that Chrome asks the user for permission each time they copy something from different website.

This makes sense from a security standpoint. Because the content script acts as if it's a script running on a webpage, it makes sense that Chrome wants to verify with the user that they trust the site. However, I'm trying to do this from a Chrome extension, so ideally the user should just have to "trust me" once. For my purposes, it's too much of an inconvenience for the user to have to hit the "Allow" button on each new page from which they copy something.

I've been looking around for something in the Chrome APIs that would help me in this case, but I've been unsuccessful. I see that it's possible to manually copy something for the user, but I'd like to see what the user is copying themselves. Is what I'm looking for possible?

EDIT:

Another potential workaround: I could call window.getSelection().toString() to see what the user currently has highlighted, and assume that that's what was just copied. However, it seems like this might not always produce the correct results, and dependence on this workaround seems like it could be a mistake. Is this the best solution?