Brian
Brian

Reputation: 4344

JavaScript in Chrome Extension returns "cannot read property 'XXX' of undefined

I've been working on a simple Chrome Extension and I have the context menu showing properly, but I can't get the popup to open. I'm trying to get it to differentiate actions based on the selection.

UPDATE

After messing for hours, I think I'm closer, but now I'm getting a "Cannot read property 'linkUrl' of undefined" and I can't figure out where it's coming from.

function getEmail(info,tab) {
    chrome.windows.create({
        url: "https://mail.google.com/mail/?ui=2&view=cm&fs=1&tf=1&shva=1&to="+info.linkUrl.substr(7), 
        width:640,
        height:700,
        focused:true,
        type:"popup",
    })
}

function sendEmail(info,tab) {
    chrome.windows.create({
        url: "https://mail.google.com/mail/?ui=2&view=cm&fs=1&tf=1&shva=1&to=" +info.selectionText,
        width:640,
        height:700,
        focused:true,
        type:"popup",
    })
}

chrome.contextMenus.create({
    title: "Send a New Email",
    contexts:["link", "selection"],
    onclick: checkType(),
});

function checkType(info,tab) {
    if (typeof info.linkUrl === $('a[href^="mailto:"]')) {
        console.log("This should print first");
        // getEmail();
    }
    else { 
        console.log("This should print");
        // sendEmail();
    }
}

manifest.json

{
   "background": {
      "scripts": [ "background.js" ]
   },

   "description": "Creates a context menu option which copies the selected address into a new Gmail compose window.",

   "manifest_version": 2,
   "name": "New Gmail Window",
   "permissions": [ "tabs", "contextMenus" ],
   "version": "0.1"
}

Upvotes: 0

Views: 1859

Answers (2)

gkalpak
gkalpak

Reputation: 48212

This line: onclick: checkType(), attempts to set the return value of checkType() as the handler for the onclick event. Immediately invoking checkType() without passing any parameters results in the "Cannot read property 'linkUrl' of undefined" error.

The correct way to register a handler would be:

...
onclick: checkType,
...

Upvotes: 0

CD..
CD..

Reputation: 74096

I think your checkType function should be fixed:

function checkType(info,tab) {
    if (info.linkUrl === $('a[href^="mailto:"]')) {
        getEmail(info, tab)
    }
    else { 
        sendEmail(info, tab);
    }
};

Upvotes: 1

Related Questions