ptr
ptr

Reputation: 3384

closing a window opened with javascript after the request has sent

Is there a way to close a window on load when opening a url in a new window with javascript (to a different origin)?

The following works fine:

var callWindow = $window.open("http://myexternalsite/?stuff=blah", "_blank");
callWindow.close();

but obviously it closes the window before the request to http://myexternalsite/?stuff=blah has sent. I don't care about getting a response back, only ensuring that the request completes.

I can't add the window.close() event to the response page because that's not the script that opened it... so seemingly all I'm left with is a manual timeout and hope it completes in time.

I also can't just do this as a simple http request because the site runs on https and the call is to an (internal network) server that does not have an ssl certificate.

Upvotes: 1

Views: 1503

Answers (1)

Lennholm
Lennholm

Reputation: 7470

You need to make the page in the window you're opening tell your page that it has loaded. The best way to do this is to use postMessage.

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

First, your page needs to start listening for messages:

window.addEventListener("message", messagelistener);

Second, the page you're loading in the new window has to post a message to its opener (your page):

window.opener.postMessage(message, targetOrigin);

targetOrigin is a string that must match the host of your page (protocol + hostname + port)

You need to create the messageListener event handler function. In this you should verify that event.origin is the page you opened so that this message is actually from that page.

The message you send from the opened page can be used to verify that everything went OK or not, or you can send whatever and in your messageListener just assume that any message from the opened page meant it loaded OK.

If you in your messageListener function determine that the opened page has verified that it should be closed, you close it.

Upvotes: 1

Related Questions