简体   繁体   English

如何关闭由window.open打开的窗口?

[英]How to close window opened by window.open?

How do I close a window opened by window.open? 如何关闭由window.open打开的窗口? Currently I have a reactjs app with a server side that handles OAuth. 目前,我有一个带有处理OAuth的服务器端的reactjs应用。

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). 流程如下:1)用户单击按钮并打开一个新窗口,该窗口重定向到服务器端(服务器端重定向到身份验证服务)。 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. 2)服务器端在身份验证成功后向客户端发出套接字io事件,以及收到的用户信息。3)通过window.open()打开的窗口最终将被关闭。

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(). 我试图在socket.on()中执行window.close(),但是它关闭了错误的窗口,而不是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. 我还尝试在发出socket io事件后在服务器端添加window.close(),但它也没有做任何事情。 Any help is much appreciated. 任何帮助深表感谢。

You need to keep a reference to the opened window and call close on that. 您需要保留对打开的窗口的引用,并在其上调用close。

const opened = startAuth();

opened.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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