Jaison Brooks
Jaison Brooks

Reputation: 5826

Chrome Extension - Determining selection text or page in Context Menu

I'm currently trying to determine if my Selection Text is Null or if my contexts = ["page"].

Currently im unsure how to write the proper if and else statement to reference the "contexts" and/or if the selectionText is null. currently i've written the below code, but this is currently not actually doing anything when the menu item is clicked.

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

Upvotes: 1

Views: 1565

Answers (1)

Métoule
Métoule

Reputation: 14472

If you want to know if the context is page, you can create another context menu solely for page context:

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

That way, you can distinguish from both:

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

Note that I used typeof info.selectionText === "undefined" rather than info.selectionText == "". Since the documentation says it's an optional parameter of info, it will be undefined rather than the empty string.

Upvotes: 4

Related Questions