I found the following solution:
- Set up a manifest file to define a content script that is added to every page, and a separate background page.
- In the Content Script .js file, add an event listener for the 'copy' event, either for the document or the window. This event listener is called whenever the user initiates a copy action.
- Since content scripts exist in a security sandbox (e.g., no cross-site XMLHttpRequests), we probably want to respond to the event in the background page. To do so, use the Chrome message passing API so send a message to the background page.
A small working example:
manifest.json
{
"background_page": "background.html",
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["oncopy.js"]
}
]
}
oncopy.js
// on copy event, send a message to background.html
function onCopy(e) {
chrome.extension.sendRequest({event: "copy"});
}
//register event listener for copy events on document
document.addEventListener('copy',onCopy,true);
background.html
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.event == "copy") {
alert("copy detected");
}
sendResponse({});
});