我正在尝试使用 JavaScript 在我的 Web 应用程序中打开和关闭新窗口。打开部分工作正常,但我在使用 window.close() 关闭窗口时遇到问题。
这是我的代码:
let myWindow;
//select dom element
const width = document.getElementById('width');
const height = document.getElementById('height');
//show window object properties
width.innerHTML = "Window inner with is: " + window.innerWidth;
height.innerHTML = "Window inner height is: " + window.innerHeight;
function openWindow() {
myWindow = window.open('https://www.google.com')
}
function closeWindow() {
myWindow.close();
}
<div>
<input type="button" value="Open window" onclick="openWindow()" />
</div>
<div>
<input type="button" value="close window" onclick="closeWindow()" />
</div>
这是由名为 Cross-Origin-Opener-Policy 的特定安全 HTTP 标头引起的。
网站可以指定此标头以禁止打开者(在本例中为您的页面)执行操作,特别是当它是跨域时。
特别是对于 Google,他们在此标头中指定了
same-origin-allow-popups; report-to="gws"
,因此您无法执行任何操作,因为它不在同一浏览上下文组中。
对于没有此 HTTP 标头的网站,默认为允许。例如,您可以尝试使用
https://example.com
,它应该可以工作。
这是一个重构的方法来完成所需的功能,尽管是在“弹出”窗口中:
let myWindow;
const width = document.getElementById('width');
const height = document.getElementById('height');
if (width && height) {
width.innerHTML = "Window inner width is: " + window.innerWidth;
height.innerHTML = "Window inner height is: " + window.innerHeight;
}
function openWindow() {
myWindow = window.open('example.com', '', 'width=800,height=600');
}
function closeWindow() {
if (myWindow && !myWindow.closed) {
myWindow.close();
}
}