0

I am trying to open an alert box when a window loads. Here is what I have:

var imawindow = window.open("http://google.com");
imawindow.onload() = function () {
    alert("hey");
}

What am I doing wrong? Thanks in advance!

Dudeguy21
  • 37
  • 9
  • Are you trying to show alert on the new window? or from the one it is opened ? – kirtan403 Nov 29 '15 at 19:56
  • Open console and read the error. Then fix your code like `imawindow.onload = function`. – dfsq Nov 29 '15 at 19:59
  • Even when you fix the syntax error (`onload() ` => `onload`) you cannot do this unless you are on the same domain. [See this question](http://stackoverflow.com/questions/245124/setting-onload-event-for-newly-opened-window-in-ie6). – Spencer Wieczorek Nov 29 '15 at 20:01
  • I was wanting an alert box to pop up on the page that opened the window, not on the window that was opened. – Dudeguy21 Nov 29 '15 at 20:04
  • Yes it will open the window from which it opened the new one. But for the same domain only. – kirtan403 Nov 29 '15 at 20:06

2 Answers2

0

You shouldn't execute it before you assign. Remove the (). If you wanna call the alert on the caller, then use window.opener:

imawindow.onload =  function () {
    window.opener.alert("hey");
}

And this should respect the same domain policy. The calling window, should be a relative page in your domain. Not something like you can call http://www.google.com/ from http://www.facebook.com/. But you can call it from index.html on hello.html, provided that both index.html and hello.html are in from the same domain, say http://example.com/index.html and http://example.com/hello.html

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

I would like mention that it will not work on cross-domain.

If you are opening a new page within the same domain than you will be able to achieve this by:

var imawindow = window.open("samedomainpage.html");
imawindow .addEventListener('load', functionToCall, false);

For cross-domain this will not work for security reasons. Read more about it here

kirtan403
  • 7,293
  • 6
  • 54
  • 97