简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM