Java Socket HTML response

html, http, java, sockets

I'm trying to get a Java socket to send a simple HTML response to a browser.

Here's my Java code:

    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 is a ServerSocket set to automatically pick an open port to use.

The idea is any webpage redirected to http:\\localhost:port (where port is the port server is listening to) is closed automatically.

When this code gets run, my browser receives the response and I've verified that it receives all the information that I'm sending.

However, the window/tab isn't closing, and I can't even close the tab by manually issuing a window.close(); command into the Javascript console for my browser.

What am I missing here? I know that an html page with the given content should automatically close the window/tab, so why isn't this working? I'm testing this on Google Chrome.

I've tried a more complete html webpage, but still no luck.

Here's what the browser is reporting as the page source:

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

Best Solution

To summarize the comments:

The root issue is actually the one found here, where window.close() won't close the current window/tab.

I looked up the MDN Documentation and found this:

When this method is called, the referenced window is closed.

This method is only allowed to be called for windows that were opened by a script using the method. If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script.

Apparently Google Chrome wasn't considering the current window to be opened by the script. I also tried this in Firefox which exhibits the same behavior.

To get around this, I must first open the current window using a script.

<script type="text/javascript">'', '_self', '');    window.close();</script>