我想在点击按钮时打开只有一个窗口。即使我多次单击该按钮,我只想要一个窗口(刷新的窗口)。
这是我的代码:
CODE
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
const width = 800;
const height = 500;
const left = window.screen.width/2 - width/2;
const top = window.screen.height/2 - height/2;
const windowFeatures = `width=${width},height=${height},status,resizable,left=${left},top=${top},screenX=${left},screenY=${top}`;
window.open("https://www.w3schools.com","",windowFeatures);
}
</script>
</body>
</html>
请使用仅限Javascript
帮助我更新上述问题的代码答案 0 :(得分:0)
将新窗口对象存储在变量中,并在单击按钮时检查该值。如果定义刚刚重新加载该窗口,则打开新窗口。刷新新窗口仅在域名相同时才起作用,否则由于跨源框架而抛出错误DOMException。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
let newWindow;
function myFunction() {
if (newWindow) {
newWindow.location.reload(true);
} else {
const width = 800;
const height = 500;
const left = window.screen.width / 2 - width / 2;
const top = window.screen.height / 2 - height / 2;
const windowFeatures = `width=${width},height=${height},status,resizable,left=${left},top=${top},screenX=${left},screenY=${top}`;
newWindow = window.open("https://www.w3schools.com", "", windowFeatures);
}
}
</script>
</body>
</html>
&#13;