用户在打开的窗口中搜索内容后(使用JavaScript),如何关闭打开的窗口



我目前正在网上制作一款电子游戏,它是一位百万富翁。我想出了一个主意,作为帮助之一,我可以让用户使用谷歌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

从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>

最新更新