selection and site search in chrome extension

前端 未结 2 1338
失恋的感觉
失恋的感觉 2021-01-15 23:04

I\'m trying to write google chrome extension that accepts user-selected word and user-defined web site and searches this word on that site (via Google and contextmenu).There

2条回答
  •  一个人的身影
    2021-01-15 23:35

    When you assign a function to onclick property it is not evaluated right away. By the time it is evaluated your loop is ended long time ago and ar[i] doesn't contain what you expect.

    It is a classic javascript problem which is solved with closures:

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

    We created anonymous function which is evaluated right away and returns a real event handler. The trick is that current ar[i] value will now be always available as element variable inside the closure.

提交回复
热议问题