Google Chrome扩展插件:如何检测复制操作(Ctrl-C和Edit-Copy)? [英] Google Chrome Extensions: How to detect Copy action (Ctrl-C and Edit-Copy)?

查看:433
本文介绍了Google Chrome扩展插件:如何检测复制操作(Ctrl-C和Edit-Copy)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检测用户是否已选择并复制Google Chrome扩展程序中当前有效标签中的某些内容?



看来没有合适的活动在chrome.tabs或chrome.windows中处理剪贴板。



有没有办法通过内容脚本来检测这些动作?


<我发现了以下解决方案:


  1. 设置清单文件为定义一个添加到每个页面的内容脚本和一个单独的背景页面。

  2. 在Content Script .js文件中,为'copy'事件添加一个事件侦听器,文件或窗口。只要用户启动复制操作,就会调用此事件侦听器。

  3. 由于内容脚本存在于安全沙箱中(例如,没有跨站点XMLHttpRequests),因此我们可能希望在后台页面中响应该事件。为此,请使用Chrome消息传递API,将消息发送到后台页面。

一个小例子:
$ b

manifest.json

  {
background_page:background.html,
content_scripts: [
{
matches:[http:// * / *],
js:[oncopy.js]
}
]
}

oncopy.js

  //在复制事件中,发送消息给background.html 
函数onCopy(e){
chrome.extension。 sendRequest({event:copy});


//在文档
上注册事件监听器以复制事件document.addEventListener('copy',onCopy,true);

background.html

  chrome.extension.onRequest.addListener(
function(request,sender,sendResponse){
if(request.event ==copy){
alert(copy detected);
}
sendResponse({});
});


How might I detect that a user has selected and copied some content in the currently active tab in a Google Chrome Extension?

It appears that there are no suitable Events that deal with the Clipboard in chrome.tabs or chrome.windows.

Is there a way to detect such actions through Content Scripts?

解决方案

I found the following solution:

  1. Set up a manifest file to define a content script that is added to every page, and a separate background page.
  2. 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.
  3. 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({});
  });

这篇关于Google Chrome扩展插件:如何检测复制操作(Ctrl-C和Edit-Copy)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆