Thomas Carlton
Thomas Carlton

Reputation: 5968

Open Google page in Javascript

I have the following code to open a google page and type "Hello" in the textbox.

The code opens the page but the textbox is empty.

Does anyone have an idea please ? Thanks.

<html>
<head>
<script type="text/javascript">
function getValue()
  {
    var myWindow = window.open("http://www.google.com","_self")
    myWindow.title = "Test"
    var TextBox = myWindow.document.getElementsByName("lst-ib");

    TextBox[0].value="Hello"    
  }
</script>
</head>
<body>
<form>
<input name="to" type="hidden" value="hoolah" />
<input type="button" onclick="getValue()" value="Get Value!" />
<form/>
</body>
</html>

Upvotes: 0

Views: 1751

Answers (2)

gavgrif
gavgrif

Reputation: 15509

If I understand the question - you want to be able to pass a value to a Google search from your page. Rather than accessing the DOM of an external page - you are just trying to enter a value into the search term box on the google page.

All you have to do is append a query string to the Google url (such as "http://www.google.com?query=searchTerm" and it will pass the value to the search box on the google page.

I have slightly modified your code to show this - not how i would normally do it but I wanted to keep your code in place as much as possible so you can see whats going on.

I added a search term input and the onclick event opens the window and submits the query to Google. It could have been done as a form submit as well. Note that I put the JS at the bottom of the page - increases speed of page rendering - not important for this, but good practise movingforward. I also declared the variables together instead of using 2 'var's as well.

your code (slightly modified).

<html>
<head>
</head>
<body>
<form>
<input id="searchTerm" type="text" value="" placeholder="Search term"/>
<button type="button" onclick="getValue()">Search</button>
</form>
<script>
function getValue()
    {
        var term,myWindow;
        term=document.getElementById('searchTerm').value;
        myWindow = window.open("http://www.google.com?query="+term,"_self")
    }
</script>
</body>
</html>

Upvotes: 0

Quentin
Quentin

Reputation: 943569

You cannot:

  • Access the DOM of a page on a different origin
  • Access the DOM of a page from JavaScript that was running in the same window before you loaded the new page

What you want is impossible.

(If it was possible, it would be a security problem as your JavaScript would have access to personal data belonging to your visitors and stored on other websites.)

Upvotes: 4

Related Questions