首页 > 解决方案 > 如何关闭window.open打开的窗口?

问题描述

如何关闭由 window.open 打开的窗口?目前我有一个带有处理 OAuth 的服务器端的 reactjs 应用程序。

流程是这样的: 1)用户单击按钮并打开一个重定向到服务器端的新窗口(服务器端重定向到身份验证服务)。2) 服务器端向客户端发出一个套接字 io 事件,以及身份验证成功后收到的用户信息 3) 由 window.open() 打开的窗口最终将被关闭。

相关代码贴在下面

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}`
  )
}

我尝试在 socket.on() 中执行 window.close(),但它关闭了错误的窗口,而不是 window.open() 打开的窗口。在发出套接字 io 事件后,我还尝试在服务器端添加 window.close() ,但这也没有做任何事情。任何帮助深表感谢。

标签: javascriptreactjs

解决方案


您需要保留对打开的窗口的引用并在其上调用 close。

const opened = startAuth();

opened.close();

推荐阅读