user3771413
user3771413

Reputation: 1

Can't access JavaScript variable inside function

I'm making an extension for selected text search in different search engines. One of the menu items changes if the selected string is a particular one. I have this done so far and it does what I want, except I can not make the "title" of the menu change. How do I give value to the variable "myTitle" in if statement inside the function?

Thanks in advance.

var myTitle; // if I give value here it does work, but I need the value based on the if statement bellow.

function myFunction(selectedText) {

    if(selectedText.match (/someString|SomeOtherString/)) {

        var myURL1 = 'https://someURL' + selectedText;
        chrome.tabs.create({url: myURL1});
        myTitle = "title1"; //I can not make the variable to get this value here

    }else{

         var myURL2 = 'https://someOtherURL' + selectedText;
         chrome.tabs.create({url: topicCall});
         myTitle = "title2"; //I can not make the variable to get this value here
         }
    }


chrome.contextMenus.create({
                **"title": myTitle,**  // this should change based on the selection 
                 contexts:["selection"], 
                 onclick: function (info)myFunction(info.selectionText);}                             
                 });

Upvotes: 0

Views: 48

Answers (2)

Steve Cochrane
Steve Cochrane

Reputation: 119

Perhaps, you can use chrome.contextMenus.update, after the page is loaded. You could create the menu, with default titles, but with unique IDs. Then use the above method, based on whatever the "selectedText" is, and use the IDs to replace the titles.

Upvotes: 0

Igor
Igor

Reputation: 15893

You have "cause and effect" mixed up. When chrome.contextMenus.create is called, myFunction has not executed yet and the value of myTitle has not been assigned.

Upvotes: 2

Related Questions