Html page close code

How to close current tab in a browser window?

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?

I might be late here but this is prevented by the browsers for a reason.

Think of yourself trying to close a window again and again and it’s not closing as its doing the «if no» part from your question which is ‘do nothing’.

This will be irritating for sure !

For anyone trying to close the tab programatically, I have two things to add (TL:DR;) 1 You can only close tabs that were opened with javascript (as Ryan Joy mentioned). 2 , not mentioned here: You can close the tab only if window.top.opener (the «parent» window) isn’t null.

windows.close() not working in the angular. It gives me Scripts may close only the windows that were opened by them. Warning.

21 Answers 21

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

Читайте также:  Setting bits in python

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

or you can specify a different window.

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.

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.

-1 Doesn’t work chrome 30 PC the other answers showing to open a window in the current tab and then close it work

In about:config dom.allow_scripts_to_close_windows = true might be the solution in Firefox (might be a big security risk!)

Bad side of this solution is that a get request is sent to server. But on the other side, I haven’t found any other solution.

Doing this from the Chrome console outputs «Scripts may close only the windows that were opened by it»

This method works in Chrome and IE:

As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).

@hering Well, the article is from 2006, but if you found something that works, that’s great news and perhaps will help people who read down this far. Thanks for sharing.

The question was about closing the current active tab from within that tab. As you say, it’s not possible in Chrome or Firefox. This should be the accepted answer.

Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find.

Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, with non-configured browsers (typical for publicly hosted sites) having limited functionality.

Context:

In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, most modern browsers no longer support this script, potentially for security reasons.

Current Functionality:

window.close() will work on tabs opened by a script, or by an anchor with target=»_blank» (opened in a new tab) without requiring any additional setup or configuration.

See @killstreet’s comment on @calios’s answer

Browser Specific work-arounds:

Google Chrome:

Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // @grant window.close in the UserScript header of TamperMonkey.

For example, my script (which is triggered when a button with is clicked and if ‘yes’ is pressed on the browser popup) looks like:

// ==UserScript== // @name Close Tab Script // @namespace http://tampermonkey.net/ // @version 1.0 // @description Closes current tab when triggered // @author Mackey Johnstone // @match http://localhost/index.php // @grant window.close // @require http://code.jquery.com/jquery-3.4.1.min.js // ==/UserScript== (function() < 'use strict'; $("#close_page").click(function() < var confirm_result = confirm("Are you sure you want to quit?"); if (confirm_result == true) < window.close(); >>); >)(); 

Note: This solution can only close the tab if it is NOT the last tab open however. Specifically, it cannot close the tab if it would cause the window to close.

Firefox:

Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.

This allows you to use the window.close() method directly in your jQuery file as you would any other script.

For example, this script works perfectly with the preference set to true:

This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn’t require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.

Edge:

Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.

Edit: This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions

MS Edge close tab confirm box

Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.

Источник

Window.close()

Функция Window.close() закрывает текущее окно или окно, которое было открыто с помощью функции Window.open() .

Этот метод разрешено использовать только для окон, которые были открыты с помощью функции window.open() (en-US). Если окно не было открыто посредством JavaScript, в консоли появится ошибка, похожая на эту: Scripts may not close windows that were not opened by script.

Синтаксис

Примеры

Закрытие окна, открытого с помощью window.open()

В примере показаны два метода, в которых первый из них открывает окно, а второй закрывает; этот пример иллюстрирует как использовать Window.close() для закрытия окна, открытого с помощью функции window.open() (en-US).

// Глобальная переменная, хранящая ссылку на открыток окно var openedWindow; function openWindow()  openedWindow = window.open('moreinfo.htm'); > function closeOpenedWindow()  openedWindow.close(); > 

Закрытие текущего окна

В прошлом, если бы вы вызвали функцию close() объекта window, вместо вызова функции close() для созданного окна, браузер закрыл бы текущее окно, создал ли его ваш скрипт или нет. В текущее время этого не произойдёт; по причинам безопасности, скриптам больше не разрешено закрывать окна, которые они не открыли. (Firefox 46.0.1: scripts can not close windows, they had not opened)

function closeCurrentWindow()  window.close(); > 

Спецификация

Совместимость с браузерами

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on 17 окт. 2022 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

«Close» button on the page

window.close() or self.close() to close the present window.

To prevent the browser from prompting the warning, you need to set the opener property and then call the close.

  var CloseWindow = function() 

try changing window.opener = «something» to window.top.opener = null, updated the post, let me know if this worked

(some browsers won’t allow this if the window wasn’t opened by a script, depending on the security features enabled)

You can do this inline pretty easily. on a div, you would do

onClick="javascript:window.close();" 
href="javascript:window.close();" 

@TRAVA If you check the javascript console you’ll probably see something like «Warning: Scripts may not close windows that were not opened by script.» — that’s the security thing I was talking about in my answer

I came to this page looking for an answer to the question while implementing in-person signing using v6.0.0-rc of the DocuSign.ESign.dll. The error was:

UNKNOWN_ENVELOPE_RECIPIENT «The recipient you have identified is not a valid recipient of the specified envelope»

The answer I found was simple: The signer.Name and signer.Email have to be the same as the view options when you pass control to apiClient.envelopeApi.CreateRecipientView()

Here is the inPersonSigner partial code

 InPersonSigner signer = new InPersonSigner(); signer.SignerName = signerName; signer.HostName = recipientName; 

And here is the code to pass control to the browser to begin a signing-session in the same browser.

 RecipientViewRequest viewOptions = new RecipientViewRequest() < ReturnUrl = "https://www.cnn.com", // your URL here ClientUserId = "1234", AuthenticationMethod = "email", UserName = signerName, Email = signerEmail >; ViewUrl viewUrl = apiClient.envelopeApi.CreateRecipientView(accountId, envelopeSummary.Data.EnvelopeId, viewOptions); 

I have no idea if this is enough information to answer your question. I’m assuming that you are running a web page that is signing a document. But instead of sending an email via a DocuSign Signer object, you are doing in-person signing session (on the same browser) using the InPersonSigner object instead. If this isn’t what you’re doing, then my answer is inappropriate. But it worked for the situation I’m describing. And the question (above) is clearly dealing with DocuSign. possibly an older version.

Источник

Оцените статью