通过Chrome扩展程序中的上下文菜单选项复制所选文本

时间:2015-01-11 21:24:37

标签: javascript google-chrome google-chrome-extension contextmenu clipboard-interaction

我正在尝试创建一个上下文菜单选项,将一些文本复制到系统剪贴板。

目前,我只是复制一个硬编码的字符串文字,但我想知道如何更改它来复制所选文本。具体来说,我不知道如何正确创建createProperties对象(见底部)

据我了解,这只能通过背景页面来完成。

我有以下背景页面:

background.html

<textarea id="temp"></textarea>
<script src="context.js"></script>

context.js如下:

chrome.contextMenus.create({
    "title": "Freedom",
    "contexts": ["editable"],
    "onclick" : copyToClipboard
  });        

function copyToClipboard()
{ 
    var tempNode = document.getElementById("temp");
    tempNode.value = "some text";
    tempNode.select();
    var status = document.execCommand('copy',false,null);

    if(status) alert('successful');

    else alert('unsuccessful');
}    

我的manifest.json如下:

{
    "manifest_version": 2,

    "name": "Freedom",
    "description": "Provides users useful and fun context menu options that they can access from anywhere.",
    "version": "1.0",

    "permissions": [
        "contextMenus",
        "clipboardWrite"
        ],  

    "background": {
        "page": "background.html"
    }   

}    

我显然是错误地声明了chrome.contextMenus.create()函数。我已经阅读了它的文档,我只能想象我没有正确创建createProperties对象。

我一直试图模仿这些来源:

Is that possible calling content script method by context menu item in Chrome extension?

http://paul.kinlan.me/chrome-extension-adding-context-menus/

其他一些相关问题是:

Copy to Clipboard in Chrome Extension

How to copy text to clipboard from a Google Chrome extension?

1 个答案:

答案 0 :(得分:2)

文档中的

"createProperties"是传递给chrome.contextMenus.create方法的字典(即&#34; title&#34;,&#34; contexts&#34;等等。 )

onclick event description of chrome.contextMenus.create表示该函数接收两个参数。第一个参数(&#34; info&#34;)是一个包含所选文本信息的字典。第二个参数(&#34;标签&#34;)包含有关标签的信息(在您的情况下,您根本不需要)。
&#34;信息&#34;字典有一个属性&#34; selectionText&#34;单击上下文菜单项时保存所选文本。这可以在您的代码中使用,如下所示:

function copyToClipboard(info) {
    var tempNode = document.getElementById("temp");
    tempNode.value = info.selectionText; // <-- Selected text
    tempNode.select();
    document.execCommand('copy', false, null);
}

这可以解决你的直接问题 除此之外,您可以通过将background page转换为event page来改进您的扩展程序。事件页面在后台页面上的主要好处是,您的扩展程序在后台闲置时不会不必要地使用内存。

// background.js

// Register context menu
chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        "id": "some id",  // Required for event pages
        "title": "Copy selected text to clipboard",
        "contexts": ["editable"],
        // "onclick" : ...  // Removed in favor of chrome.contextMenus.onClicked
    });

});

// Register a contextmenu click handler.
chrome.contextMenus.onClicked.addListener(copyToClipboard);

这是一个最小的manifest.json(注意"persistent": false键,它指定你要使用event page

{
    "manifest_version": 2,

    "name": "Copy selected text to clipboard",
    "version": "1.0",

    "permissions": [
        "contextMenus",
        "clipboardWrite"
     ],

    "background": {
        "page": "background.html",
        "persistent": false
    }
}