简体   繁体   中英

Adding live search in google chrome extension

Is there a possibility to use live autocomplete google search in your own extension? So that user given an input changing that triggers google search with results via JSON or any other convenient format.

谷歌浏览器实时搜索

I suppose that may be hijacked using AJAX calls to google.com/?q= with further parsing the HTML results, but that seems not very clear technique.

I've also checked the Google chrome API index but didn't find relevant items.

This is not in the official documentation, but digging in other extensions code, showed that this can be achieved via using JSONP requests to https://suggestqueries.google.com/ url.

Below is the sample code using jQueryUI autocomplete widget width further redirect to Google search results:

$("#googleSearch").autocomplete({
    source: function(request, response) {
            $.ajax({
                url: "https://suggestqueries.google.com/complete/search?client=chrome&q=",
                dataType: "jsonp",
                data: {
                    q: request.term
                },
                success: function(data) {
                    response(data[2].splice(0, 15));
                }
            });
        },
        minLength: 1,
        select: function(event, ui) {
            var value = ui.item.label;

            if (ui.item.label.indexOf("http://") === -1 && ui.item.label.indexOf("https://") === -1) {
                value = "http://google.com/search?q=" + value
            }

            document.location = value;
        }
    });

If using this approach, the following CSP must be in manifest.json :

"content_security_policy": "script-src 'self' 'unsafe-eval' https://suggestqueries.google.com/complete/ https://ajax.googleapis.com/ajax/services/feed/ https://*.googleapis.com/ https://www.google.com/; object-src 'self'",

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