9

I am new to javascript. I would like to know how a new window can be opened from a javascript method, and then call it's javascript methods.

The url of the window, is in another domain (can cause a security problem !?), and I don't have control over it.

For example, a code that should behave as the followings:

handler<-openAWindow("www.someurl.com");//open a window and get a handler for it
handler->someMethod1(param1, param2);//call some javascript method 
handler->someMethod2(param3, param4);//call some other javascript method<br>

Thanks,
Eran.

Sharjeel Aziz
  • 8,495
  • 5
  • 38
  • 37
user455416
  • 91
  • 1
  • 1
  • 2

1 Answers1

17

You cannot control or access a cross domain window unfortunately. This is done for security precautions. Do you have control over the other URL?

However, if the window is on the same domain you do have access to the window and its DOM.

var win = window.open("/page", "title");
win.someFunction();
var el = win.document.getElementById("id123");
//etc.
Cristian Sanchez
  • 31,171
  • 11
  • 57
  • 63
  • @Sarfraz: Well, unfortunately for him at least. But yes, it's best that this precaution was implemented otherwise people could do a lot of naughty things. :) – Cristian Sanchez Sep 22 '10 at 18:40
  • 3
    This did not work for me, since win.someFunction() would not be ready/defined yet straight after creating the new window - so I had the new window call window.opener.child_ready(), which in turn would run win.someFunction(). If there's a better way, glad to hear about it, otherwise maybe this will help someone. – MSpreij Sep 06 '14 at 01:33
  • @MSpreij, that did help me. I had a situation where I had to pass an ID to a separate page, but not using POST or GET. It sets window.note_id = 1, then runs window.open() and the opening page tests for presence of window.opener.note_id. If it exists, it processes what I need it to do. Thanks for the suggestion, it helped me get where I needed to go. – Furbeenator Nov 19 '16 at 01:16
  • To access the document element of a new window, I had to use `yourVariableName.content.document`. And to access the document element of an iframe, I had to use `yourVariableName.contentWindow.document`. But I was not able to execute a JavaScript code that reads DOM content and compares it to a specific value, even on the same domain name. In fact it looks like we can only print values in the web console but not store it in a variable. So I ended up using a Greasemonkey script. – baptx Jun 15 '20 at 19:07