8

我正在尝试使用上下文菜单项来调用我用内容脚本编写的方法。
那可能吗?

正如我所尝试的那样,上下文菜单只能在后端做事。
例如

// A generic onclick callback function.
function genericOnClick(info, tab) {
console.log("item " + info.menuItemId + " was clicked");
console.log("info: " + JSON.stringify(info));
console.log("tab: " + JSON.stringify(tab));
}

// Create one test item for each context type.
var contexts = ["page","selection","link","editable","image","video",
            "audio"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test '" + context + "' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                   "onclick": genericOnClick});
console.log("'" + context + "' item:" + id);
}

此示例无法在当前页面上记录信息,而是在背景页面上记录信息。

我有一个内容脚本可以在指定页面上生成一些内容:

var showInfo = function(){ var dialogBoxWrapper = document.createElement("div");
document.body.appendChild(dialogBoxWrapper);}

我需要通过上下文菜单调用这个函数。我该怎么办?

4

1 回答 1

15

您可以参考以下代码作为参考,在单击上下文菜单时,将调用内容脚本中的函数。

示例演示

清单.json

{
    "name": "Content to Context menu",
    "description": "http://stackoverflow.com/questions/14452777/is-that-possible-calling-content-script-method-by-context-menu-item-in-chrome-ex",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "myscript.js"
            ]
        }
    ],
    "permissions": [
        "contextMenus"
    ]
}

背景.js

function genericOnClick(info, tab) {
    console.log("item " + info.menuItemId + " was clicked");
    console.log("info: " + JSON.stringify(info));
    console.log("tab: " + JSON.stringify(tab));

    //Add all you functional Logic here
    chrome.tabs.query({
        "active": true,
        "currentWindow": true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "functiontoInvoke": "showInfo"
        });
    });
}

// Create one test item for each context type.
var contexts = ["page", "selection", "link", "editable", "image", "video",
    "audio"];
for (var i = 0; i < contexts.length; i++) {
    var context = contexts[i];
    var title = "Test '" + context + "' menu item";
    var id = chrome.contextMenus.create({
        "title": title,
        "contexts": [context],
        "onclick": genericOnClick
    });
    console.log("'" + context + "' item:" + id);
}

myscript.js

var showInfo = function () {
    console.log("Show Info is invoked");
}
var showAnotherInfo = function () {
    console.log("Show Another Info");
}
chrome.extension.onMessage.addListener(function (message, sender, callback) {
    if (message.functiontoInvoke == "showInfo") {
        showInfo();
    }
    if (message.functiontoInvoke == "showAnotherInfo") {
        showAnotherInfo();
    }
});

参考

于 2013-01-23T06:29:54.967 回答