Event close windows 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 секунд.

Capture the close event of popup window in JavaScript

I need to perform some action before a popup window(using window.open ) closes.

Something like will be good:

How can I achieve that?

7 Answers 7

Your example will work as long as the pop-up window url is in the same domain as the parent page, and you change the event to all lowercase:

While the accepted answer is correct for same origins I found a solution for cross origin popups:

For those considering using it.

Even Facebook is using this «hack» in their Javascript SDK.

You can verify this by having a look at their code. Just search for .closed in https://connect.facebook.net/en_US/sdk.js.

The event name is onbeforeunload and not onBeforeUnload . JS is case sensitive.

You need to bind the onbeforeunload event to the window AFTER it is opened.

The simplest way to do that would be to have the javascript onbeforeunload code within the window source code.

For detailed explanations, refer to these two very similar questions here and here on Stackoverflow.

onbeforeunload event must be added after loading of pop-up window. For example, you can add it at the end of its load event like below;

As stated above, you need to bind the onbeforeunload event to the window after it is opened.

You can also check if new_window.window is null . But you need to manually check it with setTimeout or setInterval functions.

This is btw the only way how to check it when you are not on the same domain.

Detect Close windows event by jQuery

Could you please give me the best way to detect only window close event for all browsers by jQuery?

I mean clicking X button on the browser or window.close() , not meaning F5 , form submission, window.location or link. I was looking for many threads but have not found the right way yet.

6 Answers 6

There is no specific event for capturing browser close event.

You can only capture on unload of the current page.

By this method, it will be effected while refreshing / navigating the current page.

Even calculating of X Y postion of the mouse event doesn’t give you good result.

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

The unload() method was deprecated in jQuery version 1.8.

so if you are using versions older than 1.8

and if you are using 1.8 and higher

hope this will work 🙂

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

Combine the mousemove and window.onbeforeunload event :- I used for set TimeOut for Audit Table.

You can solve this problem with vanilla-Js:

Unload Basics

If you want to prompt or warn your user that they’re going to close your page, you need to add code that sets .returnValue on a beforeunload event:

There’s two things to remember.

Most modern browsers (Chrome 51+, Safari 9.1+ etc) will ignore what you say and just present a generic message. This prevents webpage authors from writing egregious messages, e.g., «Closing this tab will make your computer EXPLODE! 💣».

Showing a prompt isn’t guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn’t interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should not be able to prompt you that it’s closing.

Optionally Show

You can add a simple condition to control whether to prompt your user by checking something within the event handler. This is fairly basic good practice, and could work well if you’re just trying to warn a user that they’ve not finished filling out a single static form. For example:

But if your webpage or webapp is reasonably complex, these kinds of checks can get unwieldy. Sure, you can add more and more checks, but a good abstraction layer can help you and have other benefits—which I’ll get to later. 👷‍♀️

Promises

So, let’s build an abstraction layer around the Promise object, which represents the future result of work- like a response from a network fetch() .

The traditional way folks are taught promises is to think of them as a single operation, perhaps requiring several steps- fetch from the server, update the DOM, save to a database. However, by sharing the Promise , other code can leverage it to watch when it’s finished.

Pending Work

Here’s an example of keeping track of pending work. By calling addToPendingWork with a Promise —for example, one returned from fetch() —we’ll control whether to warn the user that they’re going to unload your page.

Now, all you need to do is call addToPendingWork(p) on a promise, maybe one returned from fetch() . This works well for network operations and such- they naturally return a Promise because you’re blocked on something outside the webpage’s control.

Run JavaScript code on window close or page refresh?

Is there a way to run a final JavaScript code when a user closes a browser window or refreshes the page?

I’m thinking of something similar to onload but more like onclose? Thanks.

I don’t like the onbeforeunload method, which always yields to a confirmation box popping up (leave page/ stay on mozilla) or (reload/ don’t reload on chrome). Is there a way to execute the code quietly?

8 Answers 8

There is both window.onbeforeunload and window.onunload , which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener :

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn’t supported by Opera, as far as I know, but you could always set both.

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null . This executes the wanted code without a confirmation box popping-up. It goes something like this:

Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as «offline», or to log when they are done their session.

Historically, you would send an AJAX request in the beforeunload function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.

Later came navigator.sendBeacon() . By using the sendBeacon() method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it’s sent asynchronously, and it doesn’t impact the loading of the next page.

Unless you are targeting only desktop users, sendBeacon() should not be used with unload or beforeunload since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.

Here is an example of its usage:

When the user returns to the page, document.visibilityState will change to ‘visible’ , so you can also handle that event as well.

sendBeacon() is supported in:

  • Edge 14
  • Firefox 31
  • Chrome 39
  • Safari 11.1
  • Opera 26
  • iOS Safari 11.4

It is NOT currently supported in:

Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.

Update:

It might be worth mentioning that sendBeacon() only sends POST requests. If you need to send a request using any other method, an alternative would be to use the fetch API with the keepalive flag set to true , which causes it to behave the same way as sendBeacon() . Browser support for the fetch API is about the same.

Читайте также:  Windows server 2016 slic
Оцените статью