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?
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.
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.
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.
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/
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With