2

Is there a way to open a new browser window/tab in javascript and have it automatically search some text using the browser's default search engine? Similar to just typing text in the browsers address bar.

I've tried just window.open(search_text) and this results in both IE and chrome trying to navigate to the search_text.

nannstep
  • 85
  • 1
  • 8
  • Under `Similar to just typing text in the browsers address bar` you mean 1) when you type text in address bar it search automatically in google or 2) typing text in control+f text input – Armen Feb 26 '16 at 19:06
  • 1. When I type a string in the address bar, that is not a url, and press enter. The browser automatically performs a search on the string with the default search engine. – nannstep Feb 26 '16 at 19:27
  • So then @MysterX answers on your question – Armen Feb 26 '16 at 19:28

2 Answers2

3

May be it will be useful (if you like Google):

window.open('https://www.google.com/?#q=text_to_search')

or

window.location.replace('https://www.google.com/?#q=text_to_search')
MysterX
  • 2,318
  • 1
  • 12
  • 11
  • 3
    I think this is the best you'll be able to do. You can't use the browser's default search engine from a webpage (you'd need a browser plugin for that). You'll have to pick a search engine for them, like MysterX shows. – DaveS Feb 26 '16 at 19:10
  • Ok that was my fallback. I was hoping you could format the search text string in a way that browsers would know to search on it vs trying to navigate. I might just hardcode a search engine based on known browser types then have a default. – nannstep Feb 26 '16 at 19:19
1

I guess if you wanted google search results, you could do something like this:

function search(query){
    window.location="https://www.google.co.uk/#q="+query;
    //using window.location, could use window.open..
}

Unfortunately you cannot open it in a new tab (it would appear) using JavaScript, mainly because most web users will have settings to prevent JavaScript from doing so (mainly to stop spam). That said, all browsers seem to handle window.open differently.. Here's a related resource.

Community
  • 1
  • 1
Matthew Spence
  • 986
  • 2
  • 9
  • 27