简体   繁体   中英

selection and site search in chrome extension II

follow-up to this . I'm almost there. But there's one problem. When i enter sites at options page and click save button, contextmenu items are not updated. in order to replace them with new ones i have to reload extension!! How do i fix this?? maybe i must use remove or update Extension API methods?? How??

my code now:

manifest.json:

{
  "name": "Context Site Search",
  "version" : "0.0.0.1",
  "background_page" : "bg.html",
  "options_page": "options.html",
  "permissions" : [
    "tabs",
    "contextMenus",
    "http://www.google.com"
    ]
}

options.html

function save() { // save button click event handler


var nodes = document.querySelectorAll("input[type=text]");
for (var i=0; i<nodes.length; i++){
    if (nodes[i].value == "" ){
        alert('Enter Data!');return false;
} else {
 arr.push( nodes[i].value);


   }}


localStorage['arr'] =  JSON.stringify(arr);

if (localStorage["arr"]){
var elem = document.getElementById("sav").textContent = "Saved!";

}



}

background.html:

<script type="text/javascript">

var ar =  JSON.parse(localStorage.getItem("arr"));

for (var i  in  ar)  {


chrome.contextMenus.create({
    "title": "find ' %s' в "+ ar[i],
    "contexts": [ "selection"],
    "onclick" : (function(element){
          return function(info, tab) {
    var baseUrl = "http://www.google.com/search?q=site%3A";
    if (info.selectionText) {
    baseUrl += element + "&q="+ encodeURI(info.selectionText);
     chrome.tabs.create({"url": baseUrl});
     }
     }
     })(ar[i])


});


}


</script>

Thanks in advance!!

To update Context Menu is Chrome Extension needs to restart Chrome.

This problem seems cannot be fixed by code. Since Context menu can only be created in background page, however background page only load when the Extension started, ie Chrome started.

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