I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser.
When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, "YES" and "NO". If the user clicks "YES", close that page and If "NO", do nothing.
How can it be done? Any suggestions?
a bit late but this is what i found out...
window.close()
will only work (IE is an exception) if the window that you are trying toclose()
was opened by a script using window.open() method.you will get console error: Scripts may not close windows that were not opened by script. as an error and nothing else.
you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.
i couldn't find any way to know if the page was opened from a open() or not, and close will not throw and errors. this will NOT print "test":
you can read in MDN more about the close() function
The following works for me in Chrome 41:
I've tried several ideas for FF including opening an actual web-page, but nothing seems to work. As far as I understand, any browser will close a tab or window with xxx.close() if it was really opened by JS, but FF, at least, cannot be duped into closing a tab by opening new content inside that tab.
That makes sense when you think about it - a user may well not want JS closing a tab or window that has useful history.
Tested successfully in FF 18 and Chrome 24:
Insert in head:
HTML:
Credits go to Marcos J. Drake.
You will need Javascript to do this. Use
window.close()
:Note: the current tab is implied. This is equivalent:
or you can specify a different window.
So:
with HTML:
or:
You
return false
here to prevent the default behavior for the event. 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.This is one way of solving the same, declare a JavaScript function like this
Add the following line to the HTML to call the function using a
<button>
It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.
try this:
this will close the current tab for you.