【问题标题】:How to close an open window after the user has searched something in the open window(using JavaScript)?用户在打开的窗口中搜索了某些内容后如何关闭打开的窗口(使用 JavaScript)?
【发布时间】:2022-10-24 00:28:30
【问题描述】:
我目前正在网络上构建一个视频游戏,它是一个百万富翁。我想出了一个想法,作为帮助之一,我可以让用户使用 google 20 秒。我设法用搜索引擎打开了一个窗口,但 20 秒后我想关闭它,如果用户搜索了某些内容,这是不可能的。
newWindow=window.open('https://google.com','mywindow', 'width=375px, height=400px, top=200px')
setTimeout(() =>{
newWindow.close()
},22000)
我也看了这个教程:
https://www.youtube.com/watch?v=2Qu8mwQizbM
【问题讨论】:
标签:
javascript
html
css
window.open
【解决方案1】:
应该不可能从 JS 关闭另一个窗口,因为您的代码只能控制您的选项卡。你可以做你想做的事情的一种方法是创建一个<iframe>,然后在 20 秒后使用setTimeout() 将其删除。
你可以这样做:
const container = document.getElementById('container');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
const iframe = document.createElement('iframe');
iframe.src = 'https://google.com/';
container.appendChild(iframe);
setTimeout(() => {
iframe.remove();
}, 20000);
});
<div id="container">
<button id="btn">Use Google</button>
<br>
</div>