How to launch a google search in a new tab or window from javascript?

Jérôme Verstrynge picture Jérôme Verstrynge · May 20, 2013 · Viewed 16.7k times · Source

Say I have a Javascript variable containing a couple of search terms separated by spaces, is it possible to start a Google Search window or tab using these terms (after a user clicks on a button for example)? If yes, does anyone have a simple code example to inject in a HTML?

Answer

David Hellsing picture David Hellsing · May 20, 2013

The google search URL is basically: https://www.google.com/search?q=[query]

Using that you can easily build a search URL to navigate to, f.ex using a simple form without javascript:

<form action="http://google.com/search" target="_blank">
    <input name="q">
    <input type="submit">
</form>

Demo: http://jsfiddle.net/yGCSK/

If you have the search query in a javascript variable, something like:

<button id="search">Search</button>
<script>
var q = "Testing google search";
document.getElementById('search').onclick = function() {
    window.open('http://google.com/search?q='+q);
};
</script>

Demo: http://jsfiddle.net/kGBEy/