我目前正在尝试确定我的选择文字是否为空或我的上下文= [“页面”]。
目前我不确定如何编写正确的if和else语句来引用“contexts”和/或如果selectionText为null。目前我已经编写了下面的代码,但是当单击菜单项时,这实际上并没有做任何事情。
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");
}
答案 0 :(得分: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
的可选参数,因此它将是未定义的而不是空字符串。