views:

606

answers:

5

Using JavaScript, how can i open a new window (loading, say, http://www.google.com in the process) and inject/insert this code into its body:

<script type="text/javascript">alert(document.title);</script>

I know how to open a new window, but i don't know how to add the script to the new window and run it:

var ww = window.open('http://www.google.com');
A: 

This worked on the firebug console:

>>> var x = window.open("");
Window opened
>>> x
Window about:blank
>>> x.document
Document about:blank
>>> x.document.write("<script type='text/javascript'>alert('h1');</script>");
Alert popped up
gahooa
yes that works because you create an empty popup: i am opening an url instead, and want to add code to that page
A: 

Your ww var is a reference to the new window object. So ww.window.title would be the title of the window you have opened.

If you wish to manipulate your new window you should do it via your ww var.

andreas
A: 

@andreas: this code doesn't seem to work:

var ww = window.open("http://www.google.com");
if (window.focus) {
ww.focus();
ww.onload = alert(ww.window.document.title);
}

or in one line:

javascript:var ww = window.open("http://www.google.com");if (window.focus) {ww.focus(); ww.onload = alert(ww.window.document.title); }
+2  A: 

No. This would violate the same origin policy implemented by most (all?) browsers to protect their users.

Imagine if this were possible: You could convince users to come to your site, open a new window with, say, their bank's website loaded into it, and inject code to steal their credentials. Then proceed to steal their money, identity, etc...

Not good, eh? So be very, very glad it isn't possible.


See also: Same-origin policy for DOM access in the Browser Security Handbook

Shog9
ok thank you shog9.
A: 

The best approach is having your web-site (the one your script comes from) to act as a proxy and download url in question for you. You can therefore modify response on the server, or locally on the client.

zakovyrya