- Форум
- Справочник
- window.close
- Синтаксис
- Описание, примеры
- Close all the child window from Parent window
- Open popup and refresh parent page on close popup
- 11 Answers 11
- How to close current tab in a browser window?
- 16 Answers 16
- Google Chrome:
- Firefox:
- JavaScript метод document.close()
- Определение и применение
- Поддержка браузерами
- JavaScript синтаксис:
- Спецификация
- Пример использования
Форум
Справочник
window.close
Синтаксис
Описание, примеры
Если закрываемое окно не было открыто при помощи window.open, то
при его закрытии выводится предупреждение. Посетитель может отклонить закрытие.
А как закрыть окно если открылось не через javascript ?
А также Но будет вопрос посетителю, хочет ли он закрыть окно.
function exit() <
var thisWindow = window.open(«Listing3.html»,’_self’);
var exit = confirm(«Хотите закрыть страницу?»);
if(exit) <
thisWindow.close();
>
>
Как из родительского окна можно передать фокус окну, открытому следующей командой?
wid = window.open(‘1.htm’,’wname’,’width=300,height=300′);
wname.focus()
wid.focus()
window.wid.focus()
window.wname.focus()
self.wid.focus()
помогите плиз.
а у меня не получается закрыть окно, которое открыто не скриптом.
window.close.php
js/window.js
Подскажите как закрыть страницу через javaScript
если вставить в страницу скрипт с window.close(); то ничего не происходит..
нежно что бы при открытии страницы она закрывалась скажем через 5 секунд.
Та же проблема. Не срабатывает window.close()
Для доступа к свойствам текущего окна используется self. Используйте self.close();
Почему-то window.close(), self.close(), this.close() работают только в Opera.
Если окно создано через фрейм на jquery. Много вопросов на форумах, как закрыть модальное окно из фрейма, обычно ответ один — никак. Но решение есть и оно аналогично плагину thickbox.
Просто навесить код на элемент находящийся внутри фрейма.
По работе стоит задача сделать кнопку закрытия окна браузера без вопроса «Действительно ли вы хотите закрыть. » Пробую сейчас для IE 8 — работает прекрасно. На IE 6 — нет. Где посмотреть какими версиями експлорера поддерживается эта функциональность и нет ли аналога для шестого?
Почему все так сложно?
Работать не возможно.
Почему нельзя все упростить?
Простые вещи через жопу делать надо. Невероятно. 21 век.
Дело в том, что все упирается в политику безопасности.
Если вы хотите сделать что-бы было просто, то будьте готовы, что у вас будут «самопроизвольно» (с помощью кода в баннере например) закрываться все вкладки.
Дело в том, что все упирается в политику безопасности.
Если вы хотите сделать что-бы было просто, то будьте готовы, что у вас будут «самопроизвольно» (с помощью кода в баннере например) закрываться все вкладки.
Всегда открывал окно примерно таким кодом:
function ShowWin(src, width, height) <
obj = window.open(«», «», «scrollbars=0,dialog=0,minimizable=1,modal=1,width=»+width+»,height=»+height+»,resizable=0″ ) ;
obj.document.write(» » ) ;
obj.document.write(» » ) ;
obj.document.write(» » ) ;
>
Потребовалось закрытие окна, при клике вне него. Нашел в и-нете такой код:
Добавил в свою функцию, последней строкой, т.е. получилось:
function ShowWin(src, width, height) <
obj = window.open(«», «», «scrollbars=0,dialog=0,minimizable=1,modal=1,width=»+width+»,height=»+height+»,resizable=0″ ) ;
obj.document.write(» » ) ;
obj.document.write(» » ) ;
obj.document.write(» » ) ;
this.onfocus=function()
>
Все работает, окно закрывается при клике «снаружи».
Не понимаю, почему ONFOCUS, а не ONBLUR?
Может, кто-нибудь пояснить? Помогите пожалуйста разобраться!
Окно закрывается при клике по родительскому окну. В вашем случае, вызов функции showWin происходит в «глобальном» контексте, и внутри функции this указывает на window. Соответственно в последней строчке вы задаете обработчик получения фокуса родительским окном, а внутри обработчика — закрываете дочернее окно (которое внутри обработчка представлено переменной obj)
это какая-то магия, но работает
вызванная без аргументов, функция закрывает текущее окно
function close_window(url) <
var newWindow = window.open(», ‘_self’, »); //open the current window
window.close(url);
>
ааааа. это же просто чит !
А может ко сможет мне помочь? Мне нужно, чтоб по нажатию «ОК» в диалоговом окне alert закрывалась браузерная вкладка
Как сделать так что бы при нажатии на ОК посетитель переходил на другую страницу, а если отмена закрывалась вкладка?
Если кто мучался с закрытием модольного окна, открытого через jquery, (Например:
highslide), то вот таблетка:
играю в браузерную игру
минимальную информацию обо мне в игре можно узнать просто нажав на мой профиль
где откроется отдельное окно
но и этого я бы не хотел
там можно загрузить свою картинку (с любого сайта), вписать домашнюю страницу, оставить свою почту
вот в этих вариантах есть возможность закрытия окна с моим профилем?
что бы просто автоматически закрывалась открывшись
например когда обращается за картинкой на какой то ресурс а оттуда сразу команда закрыть окно
javascript:close() в ссылку и не парься
Есть ли способ закрыть текущую страницу в последнем chrome.
var newWindow = window.open(», ‘_self’, »); //open the current window
window.close();
Этот способ не работает.
В консоль падает warning Scripts may close only the windows that were opened by it.
Ребят, помогите.
Есть окно, из которого я открываю другое окно
var w = window.open(‘test2.html’, ‘MyWindow’);
во втором окне я делаю что надо, и жму кнопку закрыть
window.close();
как только эта страница закрывается через эту функцию, мне надо запустить скрипт на основной странице.
Как это отследить .
У меня работает только такой способ: self.close()
Доработал «читерский».
Пропишите следующего рода скрипт на закрываемую страницу.
И вызовите функцию DoCPExit();
Все успешно закрывается и без каких-либо подтверждений для пользователя.
Причем вызов функции можно настроить по времени истечения, например 5 секунд.
Close all the child window from Parent window
I want to open a Report Page such that from Login it should go to a Main Page which will itself open in a new window. On Main Page, there are two buttons. Clicking on any button it will open a particular report associated with that button in new window.
Now, the problem is there is a link on each Report Page which should go back to Main Page (i.e. It should minimise the report page). Also, if a user opens a second report again it will open in new window and hit the link to Main Page it should also minimise second report window.
Also, there is a logout on the 3 pages i.e. On Main Page, First Report and Second Report. So clicking on Logout from Main Page should close the all minimised window if there any. On clicking Logout from any other page i.e. other reports it should invalidate the session.
So the flow would be-
My problem is I am not able to close second child window when Logout is called from first. Also, if logout is called from Main page how to close all pop-up window.
Code that I am using to open Main Page from Login —
Code to open Report from Main Page —
Same code I am using to open Report 2 just I am using different URL.
On clicking logout from child I am calling this function —
Same logout function is used second child
Open popup and refresh parent page on close popup
I opened a popup window by window.open in JavaScript, i want to refresh parent page when I close this popup window.(onclose event?) how can I do that?
11 Answers 11
You can access parent window using ‘window.opener’, so, write something like the following in the child window:
The pop-up window does not have any close event that you can listen to.
On the other hand, there is a closed property that is set to true when the window gets closed.
You can set a timer to check that closed property and do it like this:
on your child page, put these:
but as a good UI design, you should use a Close button because it’s more user friendly. see code below.
when the window closes it then refreshes the parent window.
window.open will return a reference to the newly created window, provided the URL opened complies with Same Origin Policy.
This should work:
In my case I opened a pop up window on click on linkbutton in parent page. To refresh parent on closing child using
in child window caused re open the child window (Might be because of View State I guess. Correct me If I m wrong). So I decided not to reload page in parent and load the the page again assigning same url to it.
To avoid popup opening again after closing pop up window this might help,
If your app runs on an HTML5 enabled browser. You can use postMessage. The example given there is quite similar to yours.
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 ! – Muhammad Osama Mar 16 ’19 at 8:54
16 Answers 16
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.
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 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).
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, so took it on myself to do so.
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, so would not be ideal for publicly hosted sites.
Context: In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, modern browsers no longer support this script, potentially for security reasons.
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:
Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.
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.
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
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.
JavaScript метод document.close()
Определение и применение
JavaScript метод .close() объекта document завершает запись в документ (закрывает поток открытый с помощью метода open() объекта document ). Данные в поток могут быть переданы с помощью методов write() или writeln() объекта document .
Поддержка браузерами
Метод | Chrome | Firefox | Opera | Safari | IExplorer | Edge |
---|---|---|---|---|---|---|
document .close() | Да | Да | Да | Да | Да | Да |
JavaScript синтаксис:
Спецификация
Пример использования
В этом примере с использованием атрибута событий onclick при нажатии на кнопку (HTML элемент ) вызываем функцию myFunc() , которая с использованием JavaScript метода .open() объекта window открывает новое окно браузера, а с помощью метода open() объекта document открывает поток для записи этого документа. В этот документ с помощью методов write() и writeln() записываем в поток необходимые строки текста.
Основное отличие методов write() и writeln() заключается в том, что метод writeln() дополнительно добавляет символ новой строки. Это полезно, например, при работе с HTML элементом
, который сохраняет как пробелы, так и разрывы строк.
После того как мы записали в документ необходимое текстовое содержимое, мы с помощью метода .close() объекта document закрываем поток открытый с помощью метода open() объекта document .
Обратите внимание, что мы дополнительно передали в метод open() объекта document два аргумента, первый определяет тип документа (» text/html » — HTML документ по умолчанию), а второй аргумент соответствует значению » replace «, которое указывает, что пользователь, если перейдет в открытом окне на новую страницу не сможет обратно на неё вернуться (кнопка браузера «назад» будет не активна).
Результат нашего примера:
Пример создания документа в новом окне JavaScript Document