Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

html - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...