-1

Let's say I have the following code.

window.open(url, windowName, "height=500,width=500") 
// This will open a new window with the url.

myFunction();
// Run this function on the newly opened window instead of
// the old one because I need to find a link on the new page.

Right now, myFunction() is getting stuck on the old window.

Update: The new url is the another domain.

Zip
  • 5,372
  • 9
  • 28
  • 39
  • you can't. That would allow you to run javascript on arbitrary pages without the user knowing, which means you could do some very malicious things. If you are the owner of the `url` you are opening, then you can provide a mechanism on that page to read javascript from the URL parameters if you want, and execute that, but I wouldn't recommend that either. – Christian Fritz Nov 11 '15 at 04:35
  • @Christian - This is not true for the urls from same domain. – Charlie Nov 11 '15 at 04:40
  • Zip is trying to find a link on the new page. I doubt he would go through this hoop if he was in control of the new page (i.e., it's not on his domain). – Christian Fritz Nov 11 '15 at 17:59

2 Answers2

-1

Put your myFunction() in the script of the new window.

Then set the onLoad event of that window to run it.

You can get reference to your caller window's document from the new window by:

window.opener.document

There you go with enough links to do pretty much anything.

Update:

Your new window should be from the same domain. Otherwise its against the same origin policy of the browser.

Please see this question:

Ways to circumvent the same-origin policy

Community
  • 1
  • 1
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • I'm not the one who down voted, but I agree that this most likely doesn't answer the questions. Zip is trying to find a link on the new page. I doubt he would go through this hoop if he was in control of the new page. – Christian Fritz Nov 11 '15 at 18:00
  • He added that part to the question when I first talked about it in my answer. – Charlie Nov 11 '15 at 18:36
-2

You have several options:

  1. edit the source code for the webpage stored at url to include your own custom code that you want to run when the webpage opens. If you only want this code to run when the webpage opens from your popup, you could name the url something like "webpage.html?run_custom_code", then in webpage.html have javascript that only runs if window.location.href.indexOf('run_custom_code') > 0

  2. you can open a webpage that's sole purpose is to run javascript: window.open('javascript:alert()'); although based on your edit this does not seem useful to you.

  3. Use another language like PHP, where you can fetch the contents of another webpage with something like $html = file_get_contents($url);

  4. perform an ajax request to the other url (if it resides on the same domain) and scrape the results to find your link.

David Zorychta
  • 13,039
  • 6
  • 45
  • 81