5

我试图让 Java 套接字向浏览器发送一个简单的 HTML 响应。

这是我的Java代码:

    Socket socket = server.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String s;
    // this is a test code which just reads in everything the requester sends
    while ((s = in.readLine()) != null)
    {
        System.out.println(s);
        if (s.isEmpty())
        {
            break;
        }
    }
    // send the response to close the tab/window
    String response = "<script type=\"text/javascript\">window.close();</script>";

    PrintWriter out = new PrintWriter(socket.getOutputStream());
    out.println("HTTP/1.1 200 OK");
    out.println("Content-Type: text/html");
    out.println("Content-Length: " + response.length());
    out.println();
    out.println(response);
    out.flush();
    out.close();
    socket.close();

server是一个设置为自动选择要使用的开放端口的 ServerSocket。

这个想法是任何重定向到的网页http:\\localhost:portport端口server正在监听的位置)都会自动关闭。

当此代码运行时,我的浏览器会收到响应,并且我已经验证它收到了我发送的所有信息。

但是,窗口/选项卡没有关闭,我什至无法通过手动向window.close();浏览器的 Javascript 控制台发出命令来关闭选项卡。

我在这里想念什么?我知道具有给定内容的 html 页面应该自动关闭窗口/选项卡,那么为什么这不起作用?我正在谷歌浏览器上测试这个。

我尝试了一个更完整的 html 网页,但仍然没有运气。

以下是浏览器作为页面源报告的内容:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">window.close();</script>
</head>
<body>
</body>
</html>
4

1 回答 1

0

总结评论:

根本问题实际上是在这里找到的,其中 window.close() 不会关闭当前窗口/选项卡。

我查阅了MDN 文档,发现:

当这个方法被调用时,被引用的窗口被关闭。

仅允许为使用 window.open 方法的脚本打开的窗口调用此方法。如果窗口不是由脚本打开的,JavaScript 控制台中会出现以下错误:脚本可能不会关闭不是由脚本打开的窗口。

显然谷歌浏览器没有考虑脚本打开当前窗口。我也在 Firefox 中尝试过这个,它表现出相同的行为。

为了解决这个问题,我必须首先使用脚本打开当前窗口。

<script type="text/javascript">
    window.open('', '_self', '');
    window.close();
</script>
于 2012-11-22T18:46:27.577 回答