【问题标题】:How to close window opened by window.open?如何关闭window.open打开的窗口?
【发布时间】:2019-11-23 18:19:47
【问题描述】:

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

流程是这样的: 1)用户单击按钮并打开一个重定向到服务器端的新窗口(服务器端重定向到身份验证服务)。 2)服务器端向客户端发出一个socket 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() ,但这也没有做任何事情。非常感谢任何帮助。

【问题讨论】:

  • 您将open() 分配给一个变量,例如var newWindow = open(yourURL);... 然后它就像newWindow.close()。

标签: javascript reactjs


【解决方案1】:

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

const opened = startAuth();

opened.close();

【讨论】:

    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2016-08-14
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    相关资源
    最近更新 更多