Chrome 扩展程序 - 确定上下文菜单中的选择文本或页面

Chrome Extension - Determining selection text or page in Context Menu

本文关键字:选择 文本 菜单 程序 扩展 上下文 Chrome      更新时间:2023-09-26

我目前正在尝试确定我的选择文本是否为 Null 或我的上下文是否 = ["页面"]。

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

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");
 }

如果您想知道上下文是否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 的可选参数,它将是未定义的而不是空字符串。