javascript - 如何关闭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() ,但这也没有做任何事情。任何帮助深表感谢。
解决方案
您需要保留对打开的窗口的引用并在其上调用 close。
const opened = startAuth();
opened.close();
推荐阅读
- android - 如何在模块中提供应用程序实例
- amazon-s3 - 尝试使用 AWS Glue 中的笔记本创建动态框架时出现错误“java.io.FileNotFoundException:没有这样的文件或目录”
- sql - 使用管道分隔符在 SQL 查询中将一列拆分为多列
- c# - 用于获取意图的话语列表的 LUIS API 调用失败并出现 404 错误
- airflow - execution_date jinja 解析为字符串
- oracle - PLSQL 函数返回一个 clob,但不清楚它是被隐式释放还是自动释放
- assembly - 为什么这个编码会这样?
- html - 是否可以在角度 HTML 中使用 > 或 < 运算符?
- c - 如何使用批处理文件打开文件,作为批处理文件的输入
- visual-studio - 如何阻止 NuGet 打包包含不需要的文件