Chrome扩展程序“contextMenus.create”标题属性验证程序?

时间:2015-10-19 14:42:03

标签: javascript google-chrome-extension

我正在尝试根据选择显示不同的菜单文本:

manifest.js

{
  "name": "Test app",
  "description": "",
  "version": "1.0.1",
  "icons": {"16": "icons/16.png", "48": "icons/48.png", "128": "icons/128.png"},
  "permissions": ["contextMenus"],
  "background": {
    "scripts": ["js/test.js"],
    "persistent": true
  },
  "manifest_version": 2
}

JS / test.js

function validateSelection(number) {
  if (parseInt(number) > 5) {
    return "Result: x > 5; (x = " + number +")";
  } else {
    return "Result: x <= 5; (x = " + number +")";
  }
}

var s_item = chrome.contextMenus.create({"title"   : validateSelection("%s") + " => Selection: %s",
                                         "contexts": ["selection"],
                                         "onclick" : genericOnClick,
                                         "enabled" : true
                                         });

然而,无论我选择什么数字,我总是从else函数中的validateSelection()子句获得输出。什么样的对象传递给我的函数,是string?否则我可以验证selection

  1. Selected number = 4

  2. Selected number = 9

1 个答案:

答案 0 :(得分:2)

您将文字字符串"%s"传递给validateSelection,因此parseInt("%s")NaN,这就是else分支始终执行的原因。这是一个立即执行的函数,它有效地返回Result: x > 5; (x = %s),该字符串用于创建菜单项ONE TIME。然后,每当您调用菜单时Chrome都会在显示菜单时展开%s。它不能也不能将此%s AGAIN传递给validateSelection,因为它不是回调,它是根据javascript语法的即时执行函数。

上下文菜单标题不是动态的,标题没有函数回调参数。

要动态更改它,<all_urls>会在selectionchanged上注入一个document.addEventListener("selectionchange", function(e) { chrome.runtime.sendMessage({selection: getSelection().toString()}); }); 事件监听器,该监听器将在显示之前更改上下文菜单标题

内容脚本:

chrome.contextMenus.create({id: "menuSel", title: "", contexts: ["selection"]});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    .......
});

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if ("selection" in msg) {
        chrome.contextMenus.update("menuSel", {title: validateSelection(msg.selection)});
    }
});

后台脚本:

"permissions: ["tabs"]

缺点是,如果您在一个选项卡中选择某些内容而不调用上下文菜单,则切换到另一个选项卡并选择一些内容,然后切换回并立即右键单击已选择的文本,结果将是错的。但是,这可以在后台脚本中的content script侦听器中处理(可能需要manifest.json中的chrome.tabs.onActivated.addListener(function(info) { chrome.tabs.executeScript(info.tabId, {code: "getSelection().toString()"}, function(results) { chrome.contextMenus.update("menuSel", {title: validateSelection(results[0])}); } ); }); ):

allFrames: true

如果您想让它适用于帧/ iframe,请使用executeScript中的subRegex参数并确定哪个帧处于活动状态。