views:

1133

answers:

3

I want to create a link on a webpage that close current active tab in a browser without closing other tabs in browser. When user click that close link a alert message should appear asking user to confirm with two buttons, "YES" and "NO". If user clicks "YES", close that page and If "NO", do nothing.

How it will be done?

Thanks

+5  A: 

You will need Javascript to do this. Use window.close():

close();

Note: the current window is implied. This is equivalent:

window.close();

or you can specify a different window.

So:

function close_window() {
  if (confirm("Close Window?")) {
    close();
  }
}

with HTML:

<a href="javascript:close_window();">close</a>

or:

<a href="#" onclick="close_window();return false;">close</a>

You return false here to stop event propagation. Otherwise the browser will attempt to go to that URL (which it obviously isn't).

Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No). If you really want Yes and No you'll need to create some kind of modal Javascript dialog box.

Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open()) then you are allowed to close the window with javascript. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.

cletus
You can't close any tab via JavaScript."This method is only allowed to be called for windows that were opened by a script using the window.open method." In other words, you can only use JavaScript to close a window/tab that was spawned via JavaScript.
atxryan
@atxryan And I believe the *same domain/origin policy* applies as well.
Justin Johnson
+2  A: 

It cannot be done with just HTML and PHP; you will have to use JavaScript in order to do this.

Ignacio Vazquez-Abrams
Ok. JavaScript is added in question.
NAVEED
+1  A: 

Here's how you would create such a link: <a href="javascript:if(confirm('Close window?'))window.close()">close</a>

Eric Mickelsen