简体   繁体   中英

How to run Javascript in newly opened window?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM