Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 423
Jérôme Verstrynge Avatar asked May 20 '13 12:05

Jérôme Verstrynge


People also ask

How do I open a new tab with JavaScript?

To open a new tab, we have to use _blank in the second parameter of the window. open() method. The return value of window. open() is a reference to the newly created window or tab or null if it failed.

How can you open a link in a new tab browser window in HTML?

You just need an anchor ( <a> ) element with three important attributes: The href attribute set to the URL of the page you want to link to. The target attribute set to _blank , which tells the browser to open the link in a new tab/window, depending on the browser's settings.

How do you add a new page in JavaScript?

Approach: We can use window. location property inside the script tag to forcefully load another page in Javascript. It is a reference to a Location object that is it represents the current location of the document. We can change the URL of a window by accessing it.


2 Answers

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/

like image 171
David Hellsing Avatar answered Sep 25 '22 18:09

David Hellsing


Try this

<script type="text/javascript" charset="utf-8">
function search()
{
    query = 'hello world';
    url ='http://www.google.com/search?q=' + query;
    window.open(url,'_blank');
}
</script>

<input type="submit" value="" onclick="search();">

Or just

<form action="http://google.com" method="get" target="_blank">
<input type="text" name="q" id="q" />
<input type="submit" value="search google">
like image 35
Dinever Avatar answered Sep 23 '22 18:09

Dinever