在ajax调用成功后,如何关闭浏览器中当前打开的选项卡

How to close currently opened tab in browser after ajax call is success

本文关键字:选项 浏览器 成功 调用 ajax 何关闭      更新时间:2023-09-26

下面是我的ajax调用,一旦ajax调用成功,我想从浏览器关闭当前选项卡。

$.ajax({
    type: "GET",
    data: null,
    url: '@Url.Action("SessionKill", "Authentication")',
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function (response) {
        if (response != null && response.success) {
            window.location = window.close();//from here,I want to close the tab.
        }
    },
    error: function (response) {
    }
});

你打错了。试试这个:

element.close();

代替:

window.location = window.close();

窗口。关闭只能关闭带窗口打开的窗口。打开,这样你就不能在javascript中关闭当前选项卡。您可以打开一个新窗口,将其存储在一个变量中,然后关闭它。——肖恩·帕森斯

打开窗口:

var wind;
function openWindow() {
  wind = window.open("https://www.google.com/", "wind", "width=1000,height=700");
}
function closeWindow() {
  wind.close();
}
<input type="button" onclick="openWindow()" value='Open'/>
<input type="button" onclick="closeWindow()" value='Close'/>

这个代码段在堆栈溢出时被阻塞,因此不会在这里执行。

为什么window.open()被阻塞?

这对我有用:

if (response != null && response.success) {
    window.open('', '_self', ''); 
    window.close();
}

你不能关闭一个你没有用javascript打开的窗口/选项卡。

如果你用window.open()创建了一个窗口,你可以用window.close()关闭它,否则你不能用js关闭它。