1

我目前正在尝试确定我的选择文本是否为 Null 或者我的上下文 = [“page”]。

目前我不确定如何编写正确的 if 和 else 语句来引用“上下文”和/或 selectionText 是否为空。目前我已经编写了下面的代码,但是当单击菜单项时,这实际上并没有做任何事情。

chrome.contextMenus.onClicked.addListener(getword);
chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["page","selection","link","editable"];
  var title = "Chrome Extension";

chrome.contextMenus.create({
   "title": title,
   "contexts": contexts,
   "id": "main_parent"
   });
});

function getword(info,tab) {

//Currently this simply checks for which menu item was clicked.
 if (info.menuItemId == "main_parent") {
   chrome.tabs.create({ 
      url: "https://www.google.com/search?q=" + info.selectionText,
   })
 }
 //Need to determine here if the context is a "page" and/or instead if info.selectionText is null, then do something... (Current Code below doesn't do anything)
 if (info.selectionText == "") {
  alert("PAGE is selected or Selection text is NULL");
 }
4

1 回答 1

4

如果您想知道上下文是否为page,您可以单独为页面上下文创建另一个上下文菜单:

    chrome.contextMenus.onClicked.addListener(getword);
chrome.runtime.onInstalled.addListener(function() {
    var contexts = ["selection","link","editable"];
    var title = "Chrome Extension";

    chrome.contextMenus.create({
        "title": title,
        "contexts": contexts,
        "id": "context_for_all_but_page"
    });

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

这样,您可以区分两者:

function getword(info,tab) 
{

    if (typeof info.selectionText === "undefined")
        alert("Selection text is undefined");

    if (info.menuItemId === "context_for_page")
        alert("PAGE is selected");

    //Currently this simply checks for which menu item was clicked.
    if (info.menuItemId === "context_for_all_but_page" && typeof info.selectionText !== "undefined") {
        chrome.tabs.create({ 
            url: "https://www.google.com/search?q=" + info.selectionText
        });
    }
}

请注意,我使用typeof info.selectionText === "undefined"而不是info.selectionText == "". 由于文档说它是 的可选参数info,因此它将是未定义的,而不是空字符串。

于 2013-10-17T07:38:00.573 回答