Chrome谷歌浏览器使用JS关闭当前标签页

7,135 阅读1分钟

只有通过window.open()打开的页面才可以通过window.close()关闭

在之前版本的chrome浏览器中,window.close()是可以直接关闭当前标签页的,后来出于安全性的考虑,只有通过window.open()打开的页面才可以通过window.close()关闭。否则会出现如下错误提示:

Scripts may close only the windows that were opened by them.

假设我在a界面通过window.open(b)打开了b界面,在b界面中调用window.close()即可关闭b界面。

下面来探究下原理

open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;

在open方法的定义中,我们可以看到返回了一个Window类型的对象,接下来,我们去看下这个Window类型的对象有什么方法。

opener: WindowProxy | null;

close(): void;

咱们只需要调用他的close()即可关闭当前标签页了,close()销毁了我们一开始通过open()创建的对象。至于这个opener,如果不放心可以在close之前把它的值设置为null。

欢迎大家留言交流^_^