2014-10-29 47 views
0

我正在为不同搜索引擎中的选定文本搜索进行扩展。如果所选字符串是特定字符串,则其中一个菜单项会更改。到目前为止,我已经完成了这个任务,并且完成了我想要的任务,除非我无法更改菜单的“标题”。如何在函数内的if语句中赋予变量“myTitle”的值?无法访问函数中的JavaScript变量

在此先感谢。

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

回答

2

你有“因果”混淆。当调用chrome.contextMenus.create时,myFunction尚未执行且myTitle的值尚未分配。

+0

当然,不知道我是怎么错过的。是的,如果myFunction没有被调用,它永远不会运行! – 2014-10-29 14:43:28

0

也许,您可以在页面加载后使用chrome.contextMenus.update。您可以使用默认标题创建菜单,但使用唯一ID。然后使用上面的方法,基于“selectedText”是什么,并使用ID来替换标题。