Reputation: 193
How do I close a window opened by window.open? Currently I have a reactjs app with a server side that handles OAuth.
The flow is like this: 1) user clicks button and open up a new window that redirects to server side (server side redirects to authentication service). 2) server side emits a socket io event to client side alongside the user information received after authentication is successful 3) window open by window.open() finally will be closed.
The related code is pasted below
componentDidMount() {
const {
socket,
provider
} = this.props
console.log('component did mount')
socket.on(provider, user => { // Event listener
// Window should be closed at this stage after listening to event.
console.log(user)
this.setState({
user
})
this.props.addUser(user.name, 10)
})
}
startAuth() {
const {
provider
} = this.props
const width = 600,
height = 600
const left = (window.innerWidth / 2) - (width / 2)
const top = (window.innerHeight / 2) - (height / 2)
const url = `https://localhost:5000/${provider}`
return window.open(url, '', // Open window to server side
`toolbar=no, location=no, directories=no, status=no, menubar=no,
scrollbars=no, resizable=no, copyhistory=no, width=${width},
height=${height}, top=${top}, left=${left}`
)
}
I tried to do window.close() in socket.on() but it closes the wrong window, not the window opened by window.open(). I also tried to add window.close() at the server side after emitting the socket io event but that doesn't do anything as well. Any help is much appreciated.
Upvotes: 0
Views: 1842
Reputation: 21638
You need to keep a reference to the opened window and call close on that.
const opened = startAuth();
opened.close();
Upvotes: 1