简体   繁体   中英

How to close window opened by window.open?

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.

You need to keep a reference to the opened window and call close on that.

const opened = startAuth();

opened.close();

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