DEV Community

DEV Community

Google Web Dev profile image

Posted on Sep 17, 2018 • Updated on May 2, 2019

Sure you want to leave?—browser beforeunload event

In the video, I explain a bit about the beforeunload event—which lets you prompt or warn your user that they're about to leave your page. If misused, this can be frustrating for your users—why would you use it? 💁‍♂️ℹ️

✅ Your user is part way through completing a form, e.g., a purchase ✅ There's a network POST that's in-flight, e.g., saving a preference ✅ Your user is writing a blog post or a comment and it'll be lost 🤷 A video or music will stop playing ⛔ Your user hasn't finished reading an article ⛔ There's an unread email inside an email client ⛔ There's a Time Sensitive Offer! Buy Now! 🙄💸

Important To Remember

Before we get into the code, what is the tl;dr from my video? 📺👨‍🏫

  • use the beforeunload event to warn a user they're going to close your page, but only when it's important
  • a Set of Promise objects can be useful to control beforeunload
  • … and, maybe you can use sendBeacon rather than prompting at all!

If you'd like to learn more, read on! ⬇️📖

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. 👷‍♀️

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.

Busy Spinner

As I talked about in the video above 📺🔝, we can also use the set of pending work to control a busy spinner. This is a pretty simple extension to the addToPendingWork function:

When a new Promise is added, we show the spinner (by setting its .hidden property to false ). And when any promise finishes, we detect if there's no more work at all— and hide the spinner if pendingOps is empty.

I'm not a UX designer, so building a visually appealing busy spinner is a UX exercise left for the reader! 👩‍🎨

Pending Forms

But what about for the example above- a pending form? There's two options here. You could add a second beforeunload handler, just like the one at the top of this article: a simple boolean check.

But if you're interested in using the Promise mechanic even for a form, it turns out we can promisify the concept of a user completing a form. There's two parts to this idea.

First, we create our own Promise and add it to our pending work it when the user starts typing something:

Then, when the form is submitted (potentially via fetch() ), we can "resolve" that original promise with the result of the network operation:

And voilà ! If the user has typed into the form, we can block the page from unloading, using the same pending work idiom as before. Of course, your busy spinner probably shouldn't say "Saving!".

Send a Beacon

I've covered a lot on pending work, listening to the completion of promise from a fetch() . But, as I mentioned in the video, you might not always need to prompt the user at all.

If you're making a network request which has no useful result- you're just sending it to a server, and you don't care about the result- you can use the modern browser call navigator.sendBeacon() . It literally has no return value, so you can't wait for its result (whether that be success or failure). But, it's explicitly designed to run even after a page is closed.

Of course, you don't have to use sendBeacon only in beforeunload —you can use it before the page is closed, and then you might not have to implement a beforeunload handler at all, because you don't have a pending Promise to wait for!

If your browser doesn't support sendBeacon , it's almost exactly equal to sending a POST request via fetch() . You could fallback using code like this:

⚠️ It's even worth doing this if you're trying to make network requests in beforeunload , as some browsers will still succeed a fetch() even though the spec doesn't guarantee it.

Emoji Example

I use navigator.sendBeacon() to record when you select an emoji on Emojityper , to generate the 'trending' 📈 list and emoji popularity 🔥. It's suitable there as I don't need to wait for a response, and the request can go out even as you're closing the page. 😂👍

I hope you enjoyed this episode of The Standard and the slightly longer explanation!

Do you have questions? Please leave comments below, or contact me on Twitter . I'm also eager to hear your suggestions or improvements. 🕵️

Top comments (34)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

yerycs profile image

  • Joined Dec 3, 2019

Thanks for good post. I have one error, I want your help.

beforeunload function does not work if there is no user interaction. It causes following error:

Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had a user gesture since its load.

How to show warning message even no user interaction?

Hoping your help. Thanks

samthor profile image

  • Location Sydney, Australia
  • Work ¯\_(ツ)_/¯
  • Joined Feb 6, 2018

Good observation, although I actually mentioned this in the article:

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.

This makes sense—a page that I've put into a background tab and then later closed shouldn't be able to get my attention!

Thanks for your reply.

Little trick. So, is it impossible to show warning message if there is no user interaction?

There's no harm in trying (a browser might decide that the page is allowed to—perhaps if your user has visited you a lot before) but it's unlikely to work. As per my post, maybe consider using sendBeacon if there's some information you want to exfiltrate from the page before it closes...

Even calling alert() is often disallowed in background pages (or at least delayed until the page gets focus again).

Let us assume.

I have passed complex page which has decades tests. After passing this page, I get into the test result page.

If I click back button without any interaction in browser, then it goes to test page without confirmation, and I lost test result and should pass complex test again.

I hope it can be resolved. Any Idea?

Yes, that will go "back", but there are lots of other ways to store state (like your test results) that don't rely on the user keeping a page open.

e.g., indexdb, local storage, building a SPA where 'back' is handled by your code, etc ...

Understand.

Thanks for your kindly help. Hoping your good post. :)

Do you think it is impossible to implement warning message without user interaction?

Yes, I think it's impossible. Allowing an annoying popup to be generated without the user ever using the page is against what browsers are aiming for.

Can you explain about "against what browser are aiming for"? Sorry for annoying. :)

maxart2501 profile image

  • Location Italy
  • Education Mathematics
  • Work Consultant at Antreem
  • Joined Jan 12, 2017

I've always found those notifications annoying but eh, they actually saved me a couple of times.

What's way worse in my opinions is showing those "don't miss this other content!" modals when the mouse cursor leaves the boundaries of the page. They should be outright banned! 😩

To stay on topic, I think sendBeacon is a great thing - too bad IE and mobile Safari don't support it 🙁

karapapas profile image

  • Joined Mar 30, 2020

Hello! Great article on beforeunload.

I have a question though, is it possible to prevent page unload and stay on the page without prompting the user? Or, if that is not possible, to at least customize the confirmation dialog?

Thank you for your time!!

No, that's the whole point. You could write something like "CLOSING THIS PAGE WILL EXPLODE YOUR COMPUTER", and browsers have decided that you should not be able to do that.

oathkeeper profile image

  • Location Bhavnagar, Gujarat, India
  • Education B.Tech ICT
  • Work Software Engineer at Postman Inc
  • Joined Apr 5, 2018

How to ensure to know if a user has clicked on cancel on that alert? and Revert the action/API call that I was going to if user had proceeded to leave.

Inside your beforeunload handler, you can add code in a setTimeout —probably even with a timeout of zero. That code will only run if the user allowed the page to stay open.

Ok so we are basically making it async?

Yeah, because your code otherwise won't have a chance to run.

I'd probably put a longer delay than zero on it, some browsers might let code execute even if the page is closing. I admit this behavior is a bit undefined.

tux0r profile image

  • Joined Jan 2, 2017

Yes, please annoy a user who wants to leave...

This feature exists on the web whether I write about it or not! :)

Hopefully this post has given some examples of when beforeunload is appropriate to use, and detailed a technical approach so that folks don't just generate warnings all the time. And you might also save your users' data—if a network request is still pending while a page is being closed, beforeunload can be useful to ensure that it does complete successfully.

sleepyfran profile image

  • Location Prague, Czech Republic
  • Work Software Developer at Microsoft
  • Joined Aug 9, 2018

This is a super useful feature that saved me countless times in pages in which I'd lose all my progress if they didn't implement it. Of course this can be used in bad situations, just like many other features, but that doesn't mean that it can't be helpful sometimes too.

amsharma9 profile image

  • Location New Delhi
  • Work PHP Developer at Freelance
  • Joined Dec 10, 2019

I would like to know if I can differentiate between beforeunload happening when closing window and moving away from page etc. I need to logout the user when s/he closes the window but NOT when s/he is moving to another page etc.

I am using sendBeacon right now as ajax didn't work.

Moving to another page can be detected by watching focus or the Page Visibility API . The page is still open in that case, just hidden or not being used by the user.

sashirocks1 profile image

  • Joined Oct 9, 2020

I use the following piece of code in 'beforeunload' to delete a user session during logout, but this fails to clear the user session on a firefox browser, can you please help out here var req = new XMLHttpRequest(); req.open('DELETE', URI, true); req.setRequestHeader("TOKEN", $rootScope._TOKEN); req.send(null);

Don't send an XMLHttpRequest —use sendBeacon , like I mentioned in the article.

jalson1982 profile image

  • Joined May 28, 2019

Any idea how to perform graphql mutation with sendBeacon?

Well, you send off a POST request with sendBeacon . You'd tell your server (on some HTTP handler) to do something, but you wouldn't be able to see whether the result was successful.

The issue with this I can not set headers or on some way control it. I am using synchronous XMLHttp request, it runs on all browsers but slows down a little navigation and it is not also the most happier solution. I do not need to see the result I just need to save analytics data to db on browser close.

kenny08gt profile image

  • Joined Jul 27, 2019

Thanks! this is very helpful, I wish it had an option to make an action when the user actually agree to leave, like delete localstorage.

You could do the action and revert it if your JS runs again.

samishakhurana profile image

  • Location India
  • Work Software Engineer at Quinbay
  • Joined Oct 21, 2020

Hi, Thanks for an insightful post. Is there any way I can track the click of leave button on this popup. If user click on cancel button we can use setTimeOut to do some operations, but in my case I want to do some final operation on click of leave button.

rudyhadoux profile image

  • Joined Sep 16, 2019

For Angular, @HostListener( 'window:beforeunload' ) seems not working for every browsers...

pinguinosod profile image

  • Location Graz, Austria
  • Joined Jul 4, 2018

Everything works fine, except when I try to create UI tests, seems like firefox doesn't trigger beforeunload when it is being controlled by an automated software.

Unfortunately, since the browser is entirely allowed to decide whether to show this message at all (e.g. if a tab has never had focus), it might not be something you can really test in an automated fashion. 😔

tachuong20121997 profile image

  • Location VietName
  • Joined Apr 8, 2020

I use Reactjs to build the app, and "beforeunload" doesn't seem to work on iphone safari

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

whoisarjen profile image

The Power of Typescript Satisfied Operator in Less than 2 Minutes

Kamil Owczarek - May 27

sonnavigator profile image

5 HTML Tags & Attributes ที่ควรรู้สำหรับ SEO

Coffee Dev - May 4

prudkohliad profile image

How to set up a new project using Yarn

Anton Prudkohliad - May 8

mpratapdev profile image

Microfrontends and the challenges involved

Mahesh Pratap - May 4

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Safari 15 prompts the beforeunload alert, but does not block navigation

Using the example provided by MDN, the beforeunload event is working in my Safari browser:

(I first must click into the window to make sure the browser detects interaction.)

  • if I close the browser window, the alert blocks the window from being closed
  • If I navigate to another page, the alert is shown
  • However, when I navigate to another page, the alert does not block navigation.

I am taken to the new page with the alert still being displayed. The alert is then "useless" in the sense that pressing the affirmative or negative buttons dismisses the alert, but has no other effect. This is not the expected behavior in Chrome or Firefox. In these, the page will not navigate or cancel navigation until an alert option is clicked.

Is there any work-around? It seems it would be better to not show the alert at all than to show the alert while asynchronously unloading the current page and loading another page.

I need to use this event to inform a user they may want to save changes to a document before leaving the page. This was the original use case for beforeunload.

!!! It's very important in this test to wait and watch the alert. The behavior I describe is navigation, so we must wait for the link to resolve and page GET to commence before you see this issue.

This is the kind of defect you might not catch in automation testing, because unless there is a pause after the alert is shown, the test might pass.

!!!! This only happens when clicking on a bookmarked link. If you type some link into the navigation bar, it behaves as expected.

Specifically this applies to CACHED pages only.

Blazing fast. Incredibly private.

unload safari

Safari is the best way to experience the internet on all your Apple devices. It brings robust customization options, powerful privacy protections, and optimizes battery life — so you can browse how you like, when you like. And when it comes to speed, it’s the world’s fastest browser. 1

Performance

More with the battery. less with the loading..

With a blazing-fast JavaScript engine, Safari is the world’s fastest browser. 1 It’s developed to run specifically on Apple devices, so it’s geared to make the most out of your battery life and deliver long-lasting power.

unload safari

Increased performance

We’re always working to make the fastest desktop browser on the planet even faster.

unload safari

Improved power efficiency

Safari lets you do more online on a single charge.

unload safari

Up to 4 hours more streaming videos compared with Chrome 3

unload safari

Up to 17 hours of video streaming 3

Best-in-class browsing

Safari outperforms both Mac and PC browsers in benchmark after benchmark on the same Mac. 4

  • JetStream /
  • MotionMark /
  • Speedometer /

JavaScript performance on advanced web applications. 4

Safari vs. other Mac browsers

Safari on macOS

Chrome on macOS

Edge on macOS

Firefox on macOS

Safari vs. Windows 11 browsers

Chrome on Windows 11

Edge on Windows 11

Firefox on Windows 11

Rendering performance of animated content. 4

Web application responsiveness. 4

4K video streaming

See your favorite shows and films in their best light. Safari supports in-browser 4K HDR video playback for YouTube, Netflix, and Apple TV+. 5 And it runs efficiently for longer-lasting battery life.

unload safari

Privacy is built in.

Online privacy isn’t just something you should hope for — it’s something you should expect. That’s why Safari comes with industry-leading privacy protection technology built in, including Intelligent Tracking Prevention that identifies trackers and helps prevent them from profiling or following you across the web. Upgrading to iCloud+ gives you even more privacy protections, including the ability to sign up for websites and services without having to share your personal email address.

unload safari

Intelligent Tracking Prevention

unload safari

Safari stops trackers in their tracks.

What you browse is no one’s business but your own. Safari has built‑in protections to help stop websites and data-collection companies from watching and profiling you based on your browsing activity. Intelligent Tracking Prevention uses on‑device intelligence to help prevent cross‑site tracking and stops known trackers from using your IP address — making it incredibly difficult to learn who you are and what you’re interested in.

Privacy Report

Safari makes it simple to see how your privacy is protected on all the websites you visit. Click Privacy Report in the Safari menu for a snapshot of cross-site trackers currently prevented from profiling you on the website you’re visiting. Or view a weekly Privacy Report to see how Safari protects you as you browse over time.

unload safari

Customization

Putting the you in url..

Safari is more customizable than ever. Organize your tabs into Tab Groups so it’s easy to go from one interest to the next. Set a custom background image and fine-tune your browser window with your favorite features — like Reading List, Favorites, iCloud Tabs, and Siri Suggestions. And third-party extensions for iPhone, iPad, and Mac let you do even more with Safari, so you can browse the way you want across all your devices.

unload safari

Safari Profiles allow you to separate your history, extensions, Tab Groups, favorites, cookies, and more. Quickly switch between profiles for topics you create, like Personal and Work.

unload safari

Web apps let you save your favorite websites to the Dock on Mac and to the Home Screen on iPhone and iPad. A simplified toolbar and separate settings give you an app-like experience.

unload safari

Safari Extensions add functionality to your browser to help you explore the web the way you want. Find and add your favorite extensions in the dedicated Safari category on the App Store.

unload safari

Save and organize your tabs in the way that works best for you. Name your Tab Groups, edit them, and switch among them across devices. You can also share Tab Groups — making planning your next family trip or group project easier and more collaborative.

unload safari

Smart Tools

Designed to help your work flow..

Built-in tools create a browsing experience that’s far more immersive, intuitive, and immediate. Get detailed information about a subject in a photo with just a click, select text within any image, instantly translate an entire web page, and quickly take notes wherever you are on a site — without having to switch apps.

unload safari

Notes is your go-to app to capture any thought. And with the Quick Note feature, you can instantly jot down ideas as you browse websites without having to leave Safari.

unload safari

Translation

Translate entire web pages with a single click. You can also get translations for text in images and paused video without leaving Safari.

Interact with text in any image or paused video on the web using functions like copy and paste, translate, and lookup. 6

unload safari

Visual Look Up

Quickly learn more about landmarks, works of art, breeds of dogs, and more with only a photo or an image you find online. And easily lift the subject of an image from Safari, remove its background, and paste it into Messages, Notes, or other apps.

unload safari

Surf safe and sound.

Strong security protections in Safari help keep you safe. Passkeys introduce a safer way to sign in. iCloud Keychain securely stores and autofills passkeys and passwords across all your devices. Safari also notifies you when it encounters suspicious websites and prevents them from loading. Because it loads each web page in a separate process, any harmful code is always confined to a single browser tab so it won’t crash the entire application or access your data. And Safari automatically upgrades sites from HTTP to the more secure HTTPS when available.

unload safari

Passkeys introduce a more secure and easier way to sign in. No passwords required.

Passkeys are end-to-end encrypted and safe from phishing and data leaks, and they are stronger than all common two-factor authentication types. Thanks to iCloud Keychain, they work across all your Apple devices, and they even work on non-Apple devices.

Learn more about passkeys

unload safari

Apple Pay and Wallet make checkout as easy as lifting a finger.

Apple Pay is the easiest and most secure way to shop on Safari — allowing you to complete transactions with Face ID or Touch ID on your iPhone or iPad, with Touch ID on your MacBook Pro or MacBook Air, or by double-clicking the side button on your Apple Watch.

Learn more about Apple Pay

With AutoFill, you can easily fill in your previously saved credit card information from the Wallet app during checkout. Your credit card details are never shared, and your transactions are protected with industry-leading security.

Same Safari. Different device.

Safari works seamlessly and syncs your passwords, bookmarks, history, tabs, and more across Mac, iPad, iPhone, and Apple Watch. And when your Mac, iOS, or iPadOS devices are near each other, they can automatically pass what you’re doing in Safari from one device to another using Handoff. You can even copy images, video, or text from Safari on your iPhone or iPad, then paste into another app on your nearby Mac — or vice versa.

unload safari

When you use Safari on multiple devices, your tabs carry over from one Apple device to another. So you can search, shop, work, or browse on your iPhone, then switch to your iPad or Mac and pick up right where you left off.

Save web pages you want to read later by adding them to your Reading List. Then view them on any of your iCloud-connected devices — even if you’re not connected to the internet.

iCloud Keychain securely stores your user names, passkeys, passwords, and credit card numbers and keeps them up to date on your trusted devices. So you can easily sign in to your favorite websites — as well as apps on iOS and iPadOS — and quickly make online purchases.

unload safari

Designed for developers.

Deep WebKit integration between Mac hardware and macOS allows Safari to deliver the fastest performance and the longest battery life of any browser on the platform, while supporting modern web standards for rich experiences in the browser. WebKit in macOS Sonoma includes optimizations that enable even richer browsing experiences, and give developers more control over styling and layout — allowing for more engaging content.

Make Safari your default browser

Customize your start page, view your browsing privacy report, monitor your saved passwords, use apple pay in safari, view your tabs across all your devices, read the safari user guide, get safari support.

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Back/forward cache

Philip Walton

Back/forward cache (or bfcache) is a browser optimization that enables instant back and forward navigation. It significantly improves the browsing experience, especially for users with slower networks or devices.

As web developers, it's critical to understand how to optimize your pages for bfcache , so your users can reap the benefits.

Browser compatibility

bfcache has been supported in both Firefox and Safari for many years, across desktop and mobile.

Starting in version 86, Chrome enabled bfcache for cross-site navigations on Android for a small percentage of users. In subsequent releases, additional support slowly rolled out. Since version 96, bfcache is enabled for all Chrome users across desktop and mobile.

bfcache basics

bfcache is an in-memory cache that stores a complete snapshot of a page (including the JavaScript heap) as the user is navigating away. With the entire page in memory, the browser can quickly restore it if the user decides to return.

How many times have you visited a website and clicked a link to go to another page, only to realize it's not what you wanted and click the back button? In that moment, bfcache can make a big difference in how fast the previous page loads:

Check out this video of bfcache in action to understand the speed up it can bring to navigations:

In the video, the example with bfcache is quite a bit faster than the example without it.

bfcache not only speeds up navigation, it also reduces data usage, since resources don't have to be downloaded again.

Chrome usage data shows that 1 in 10 navigations on desktop and 1 in 5 on mobile are either back or forward. With bfcache enabled, browsers could eliminate the data transfer and time spent loading for billions of web pages every single day!

How the "cache" works

The "cache" used by bfcache is different from the HTTP cache , which plays its own role in speeding up repeat navigations. bfcache is a snapshot of the entire page in memory, including the JavaScript heap, whereas the HTTP cache contains only the responses for previously made requests. Since it's very rare for all requests required to load a page to be fulfilled from the HTTP cache, repeat visits using bfcache restores are always faster than even the most well-optimized non-bfcache navigations.

Creating a snapshot of a page in memory, however, involves some complexity in terms of how best to preserve in-progress code. For example, how do you handle setTimeout() calls where the timeout is reached while the page is in the bfcache?

The answer is that browsers pause any pending timers or unresolved promises for pages in bfcache, including almost all pending tasks in the JavaScript task queues , and resume processing tasks if the page is restored from the bfcache.

In some cases, such as for timeouts and promises, this is fairly low risk, but in other cases it can lead to confusing or unexpected behavior. For example, if the browser pauses a task that's required as part of an IndexedDB transaction , it can affect other open tabs in the same origin, because the same IndexedDB databases can be accessed by multiple tabs simultaneously. As a result, browsers will generally not attempt to cache pages in the middle of an IndexedDB transaction or while using APIs that might affect other pages.

For more details on how various API usage affects a page's bfcache eligibility, see Optimize your pages for bfcache .

The bfcache and iframes

If a page contains embedded iframes, then the iframes themselves are not eligible for the bfcache. For example, if you navigate to another page within an iframe, but then go back, the browser will go "back" within the iframe rather than in the main frame, but the back navigation within the iframe won't use the bfcache.

The main frame can also be blocked from using the bfcache if an embedded iframe uses APIs that block this. The Permissions Policy set on the main frame or the use of sandbox attributes can be used to avoid this.

The bfcache and Single Page Apps (SPA)

Because bfcache works with browser-managed navigations, it doesn't work for "soft navigations" within a single-page app (SPA). However, bfcache can still help when going back to an SPA rather than doing a full re-initialisation of that app again from the start.

APIs to observe bfcache

Although bfcache is an optimization that browsers do automatically, it's still important for developers to know when it's happening so they can optimize their pages for it and adjust any metrics or performance measurement accordingly.

The primary events used to observe bfcache are the page transition events pageshow and pagehide , which are supported by most browsers .

The newer Page Lifecycle events— freeze and resume —are also dispatched when pages enter or leave bfcache, as well as in some other situations, for example, when a background tab gets frozen to minimize CPU usage. These events are only supported in Chromium-based browsers.

Observe when a page is restored from bfcache

The pageshow event fires right after the load event when the page is initially loading and any time the page is restored from bfcache. The pageshow event has a persisted property, which is true if the page was restored from bfcache and false otherwise. You can use the persisted property to distinguish regular page loads from bfcache restores. For example:

In browsers that support the Page Lifecycle API, the resume event fires when pages are restored from bfcache (immediately before the pageshow event) and when a user revisits a frozen background tab. If you want to update a page's state after it's frozen (which includes pages in the bfcache), you can use the resume event, but if you want to measure your site's bfcache hit rate, you'd need to use the pageshow event. In some cases, you might need to use both.

For details on bfcache measurement best practices, see How bfcache affects analytics and performance measurement .

Observe when a page is entering bfcache

The pagehide event fires either when a page unloads or when the browser tries to put it in the bfcache.

The pagehide event also has a persisted property. If it's false , you can be confident a that page isn't about to enter the bfcache. However, persisted being true doesn't guarantee that a page will be cached. It means the browser intends to cache the page, but there may be other factors that make it impossible to cache.

Similarly, the freeze event fires immediately after the pagehide event if persisted is true , but that only means the browser intends to cache the page. It might still have to discard it for a number of reasons explained later.

Optimize your pages for bfcache

Not all pages get stored in bfcache, and even when a page does get stored there, it won't stay there indefinitely. It's critical that developers understand what makes pages eligible (and ineligible) for bfcache to maximize their cache-hit rates.

The following sections outline the best practices to make it as likely as possible that the browser can cache your pages.

Never use the unload event

The most important way to optimize for bfcache in all browsers is to never use the unload event. Ever!

The unload event is problematic for browsers because it predates bfcache and many pages on the internet operate under the (reasonable) assumption that a page won't continue to exist after the unload event has fired. This presents a challenge because many of those pages were also built with the assumption that the unload event would fire any time a user is navigating away, which is no longer true (and hasn't been true for a long time ).

So browsers are faced with a dilemma, they have to choose between something that can improve the user experience—but might also risk breaking the page.

On desktop, Chrome and Firefox have chosen to make pages ineligible for bfcache if they add an unload listener, which is less risky but also disqualifies a lot of pages. Safari will attempt to cache some pages with an unload event listener, but to reduce potential breakage it won't run the unload event when a user is navigating away, which makes the event very unreliable.

On mobile, Chrome and Safari will attempt to cache pages with an unload event listener since the risk of breakage is lower due to the fact that the unload event has always been extremely unreliable on mobile. Firefox treats pages that use unload as ineligible for the bfcache, except on iOS, which requires all browsers to use the WebKit rendering engine, and so it behaves like Safari.

Instead of using the unload event, use the pagehide event. The pagehide event fires in all cases where the unload event fires, and it also fires when a page is put in the bfcache.

In fact, Lighthouse has a no-unload-listeners audit , which will warn developers if any JavaScript on their pages (including that from third-party libraries) adds an unload event listener.

Due to its unreliability, and the performance impact for bfcache, Chrome is looking to deprecate the unload event .

Use Permission Policy to prevent unload handlers being used on a page

Sites that don't use unload event handlers can ensure these are not added by using a Permissions Policy from Chrome 115.

This also prevents third parties or extensions from slowing the site down by adding unload handlers and making the site ineligible for the bfcache.

Only add beforeunload listeners conditionally

The beforeunload event won't make your pages ineligible for bfcache in modern browsers bfcache but previously it did and it is still unreliable, so avoid using it unless absolutely necessary.

Unlike the unload event, however, there are legitimate uses for beforeunload . For example, when you want to warn the user that they have unsaved changes they'll lose if they leave the page. In this case, it's recommended that you only add beforeunload listeners when a user has unsaved changes and then remove them immediately after the unsaved changes are saved.

Minimize use of Cache-Control: no-store

Cache-Control: no-store is an HTTP header web servers can set on responses that instructs the browser not to store the response in any HTTP cache. It's used for resources containing sensitive user information, such as pages behind a login.

Although bfcache is not an HTTP cache, historically, when Cache-Control: no-store is set on the page resource itself (as opposed to any subresource), browsers have chosen not to store the page in bfcache. There is work underway to change this behavior for Chrome in a privacy-preserving manner, but at present any pages using Cache-Control: no-store won't be eligible for bfcache.

Since Cache-Control: no-store restricts a page's eligibility for bfcache, it should only be set on pages that contain sensitive information where caching of any sort is never appropriate.

For pages that need to always serve up-to-date content—and that content does not contain sensitive information—use Cache-Control: no-cache or Cache-Control: max-age=0 . These directives instruct the browser to revalidate the content before serving it, and they don't affect a page's bfcache eligibility.

Note that when a page is restored from bfcache, it is restored from memory, not from the HTTP cache. As a result, directives like Cache-Control: no-cache or Cache-Control: max-age=0 are not taken into account, and no revalidation occurs before the content is displayed to the user.

This is still likely a better user experience, however, as bfcache restores are instant and—since pages don't stay in the bfcache for very long—it's unlikely that the content is out of date. However, if your content does change minute-by-minute, you can fetch any updates using the pageshow event, as outlined in the next section.

Update stale or sensitive data after bfcache restore

If your site keeps user state—especially any sensitive user information—that data needs to be updated or cleared after a page is restored from bfcache.

For example, if a user navigates to a checkout page and then updates their shopping cart, a back navigation could potentially expose out-of-date information if a stale page is restored from bfcache.

Another, more critical example is if a user signs out of a site on a public computer and the next user clicks the back button. This could potentially expose private data that the user assumed was cleared when they logged out.

To avoid situations like this, it's good to always update the page after a pageshow event if event.persisted is true :

While ideally you would update the content in place, for some changes you may want to force a full reload. The following code checks for the presence of a site-specific cookie in the pageshow event and reloads if the cookie is not found:

A reload has the advantage that will still preserve the history (to allow forward navigations), but a redirect may be more appropriate in some cases.

Ads and bfcache restore

It may be tempting to try to avoid the use of bfcache to serve a new set of ads on each back/forward navigation. However, as well as having a performance impact, it is questionable whether such behavior leads to better ad engagement. Users may have noticed an ad they intended to return to click but by reloading rather than restoring from the bfcache they not be able to. Testing this scenario—ideally with an A/B test—is important before making assumptions.

For sites that do want to refresh ads on bfcache restore, then refreshing just the ads on the pageshow event when event.persisted is true allows this to happen without impacting the page performance. Check with your ad provider but here is one example on how to do this with Google Publishing Tag .

Avoid window.opener references

In older browsers, if a page was opened using window.open() from a link with target=_blank , without specifying rel="noopener" , the opening page would have a reference to the window object of the opened page.

In addition to being a security risk , a page with a non-null window.opener reference can't safely be put into bfcache, because that could break any pages attempting to access it.

As a result, it's best to avoid creating window.opener references. You can do this by using rel="noopener" whenever possible (note, this is now the default in all modern browsers). If your site requires opening a window and controlling it through window.postMessage() or directly referencing the window object, neither the opened window nor the opener will be eligible for the bfcache.

Close open connections before the user navigates away

As mentioned previously, when a page is put into the bfcache, it pauses all scheduled JavaScript tasks and resumes them when the page is taken out of the cache.

If these scheduled JavaScript tasks are only accessing DOM APIs—or other APIs isolated to just the current page—then pausing these tasks while the page is not visible to the user is not going to cause any problems.

However, if these tasks are connected to APIs that are also accessible from other pages in the same origin (for example: IndexedDB, Web Locks, WebSockets) this can be problematic because pausing these tasks may prevent code in other tabs from running.

As a result, some browsers won't attempt to put a page in bfcache in the following scenarios:

  • Pages with an open IndexedDB connection
  • Pages with in-progress fetch() or XMLHttpRequest
  • Pages with an open WebSocket or WebRTC connection

If your page is using any of these APIs, we strongly recommend closing connections and removing or disconnecting observers during the pagehide or freeze event. That allows the browser to safely cache the page without the risk of affecting other open tabs.

Then, if the page is restored from the bfcache, you can reopen or reconnect to those APIs during the pageshow or resume event.

The following example shows how to ensure that pages using IndexedDB are eligible for bfcache by closing an open connection in the pagehide event listener:

Test to ensure your pages are cacheable

Chrome DevTools can help you test your pages to ensure they're optimized for bfcache, and identify any issues that might prevent them from being eligible.

To test a page:

  • Navigate to the page in Chrome.
  • In DevTools, go to Application -> Back-forward Cache .
  • Click the Run Test button. DevTools then tries to navigate away and back to determine whether the page can be restored from bfcache.

Back-forward cache panel in DevTools

If the test is successful, the panel reports "Restored from back-forward cache".

DevTools reporting a page was successfully restored from bfcache

If it's unsuccessful, the panel indicates the reason why. If the reason is something you can address as a developer, the panel marks it as Actionable .

DevTools reporting failure to restore a page from bfcache

In this example, the use of an unload event listener makes the page ineligible for bfcache. You can fix that by switching from unload to using pagehide :

Lighthouse 10.0 also added a bfcache audit , which performs a similar test. For more information, see the bfcache audit's docs .

How bfcache affects analytics and performance measurement

If you use an analytics tool to measure visits to your site, you might notice a decrease in the total number of pageviews reported as Chrome enables bfcache for more users.

In fact, you're likely already underreporting pageviews from other browsers that implement bfcache, because many popular analytics libraries don't measure bfcache restores as new pageviews.

To include bfcache restores in your pageview count, set listeners for the pageshow event and check the persisted property.

The following example shows how to do this with Google Analytics. Other analytics tools likely use similar logic:

Measure your bfcache hit ratio

You may also want to measure whether the bfcache was used, to help identify pages that are not utilizing the bfcache. This can be done by measuring the navigation type for page loads:

Calculate your bfcache hit ratio using the counts for back_forward navigations and back_forward_cache navigations.

It is important to realize that there are a number of scenarios, outside of the site owners control, when a Back/Forward navigation won't use the bfcache, including:

  • when the user quits the browser and starts it again
  • when the user duplicates a tab
  • when the user closes a tab and reopens it

In some of these cases the original navigation type may be preserved by some browsers and so may show a type of back_forward despite these not being Back/Forward navigations.

Even without those exclusions the bfcache will be discarded after a period to conserve memory.

So, website owners shouldn't be expecting a 100% bfcache hit ratio for all back_forward navigations. However, measuring their ratio can be useful to identify pages where the page itself is preventing bfcache usage for a high proportion of back and forward navigations.

The Chrome team has added the NotRestoredReasons API to help expose the reasons why pages don't use bfcache, so developers can improve their bfcache hit rates. The Chrome team has also added navigation types to CrUX making it possible to see the number of bfcache navigations even without measuring it yourself.

Performance measurement

bfcache can also negatively affect performance metrics collected in the field , specifically metrics that measure page load times.

Since bfcache navigations restore an existing page rather than initiate a new page load, the total number of page loads collected will decrease when bfcache is enabled. What's critical, though, is that the page loads being replaced by bfcache restores would likely have been some of the fastest page loads in your dataset. This is because back and forward navigations, by definition, are repeat visits, and repeat page loads are generally faster than page loads from first time visitors (due to HTTP caching , as mentioned earlier).

The result is fewer fast page loads in your dataset, which will likely skew the distribution slower—despite the fact that the performance experienced by the user has probably improved!

There are a few ways to deal with this issue. One is to annotate all page load metrics with their respective navigation type : navigate , reload , back_forward , or prerender . This lets you continue to monitor your performance within these navigation types, even if the overall distribution skews negative. We recommend this approach for non-user-centric page load metrics like Time to First Byte (TTFB) .

For user-centric metrics like the Core Web Vitals , a better option is to report a value that more accurately represents what the user experiences.

Impact on Core Web Vitals

Core Web Vitals measure the user's experience of a web page across a variety of dimensions (loading speed, interactivity, visual stability), and since users experience bfcache restores as faster navigations than full page loads, it's important that the Core Web Vitals metrics reflect this. After all, a user doesn't care whether or not bfcache was enabled, they just care that the navigation was fast!

Tools that collect and report on the Core Web Vitals metrics, like the Chrome User Experience Report , treat bfcache restores as separate page visits in their dataset. And while there aren't dedicated web performance APIs for measuring these metrics after bfcache restores, you can approximate their values using existing web APIs:

  • For Largest Contentful Paint (LCP) , use the delta between the pageshow event's timestamp and the timestamp of the next painted frame, because all elements in the frame will be painted at the same time. In the case of a bfcache restore, LCP and FCP are the same.
  • For Interaction to Next Paint (INP) , keep using your existing Performance Observer, but reset the current INP value to 0.
  • For Cumulative Layout Shift (CLS) , keep using your existing Performance Observer, but reset the current CLS value to 0.

For more details on how bfcache affects each metric, see the individual Core Web Vitals metric guides pages . For a specific example of how to implement bfcache versions of these metrics, refer to the PR adding them to the web-vitals JS library .

The web-vitals JavaScript library supports bfcache restores in the metrics it reports.

Additional Resources

  • Firefox Caching (bfcache in Firefox)
  • Page Cache (bfcache in Safari)
  • Back/forward cache: web exposed behavior (bfcache differences across browsers)
  • bfcache tester (test how different APIs and events affect bfcache in browsers)
  • Performance Game Changer: Browser Back/Forward Cache (a case study from Smashing Magazine showing dramatic Core Web Vitals improvements by enabling bfcache)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-05-23 UTC.

  • 4.3 • 62.1K Ratings

Screenshots

Description.

Explore the web with lightning-fast speed, powerful privacy protections and robust customization options. With Safari you can browse sites, translate web pages, and access your tabs across iOS, iPadOS, and macOS. Features • Passwords, bookmarks, history, tabs and more seamlessly sync across iPhone, iPad and Mac • Private Browsing mode doesn’t save your history and keeps your browsing your business • Intelligent Tracking Prevention prevents trackers from following you across websites you visit • Tab Groups let you save and organize your tabs and access them across iOS, iPadOS and macOS • Profiles help keep your browsing history, website data, and more separate between topics like work and personal • Shared Tab Groups help you share tabs and collaborate with family and friends • Extensions allow you to personalize Safari and add even more functionality to the browser • Reader formats articles for easy reading without ads, navigation, or other distracting items • Privacy Report shows known trackers that have been blocked from tracking you • Reading List easily saves articles for you to read later • Voice Search lets you search the web using just your voice • Web page translation converts entire webpages into other languages right in the browser • Handoff effortlessly passes what you’re doing in Safari from one device to another • Add to Home Screen allows you to quickly launch a website or web app from your Home Screen

Ratings and Reviews

62.1K Ratings

To much scams…please READ!

So whenever I use this app/ Safari it get these trackers and scammers to get my location and this is making me nervous. I installed ad blocker I think it’s called and I blocked some trackers which made me feel better. Every time you search something you usually get a scam or tracker. I do not like when people track me down. I rarely use this app because of the scams and risks. I think it is an OK app in general because it’s the people making these small BAD websites. The reason I gave it 4 stars is because it could use work but it is pretty much like google. I use google way more because I feel like it is much safer than safari. I could be wrong… Safari could use some work with all these BAD websites. Can you block these bad websites? I would love to block these websites cause they are scary. Also watch out for nine anime/ 9anime websites… I searched up 9anime on safari and clicked a link. It looked safe but then these inappropriate pop ups kept coming. I immediately got off. I checked my ‘ How much trackers we have prevented’ or whatever it’s called it said that it had prevented 14 trackers from getting my IP address. This was good and bad news. I’m glad that safari and google can prevent these trackers but it is bad because this is dangerous. BE CAREFUL ON SAFARI!!!

Your Underrated Prince, Safari

In my humble opinion, Safari is the underrated king among multiple web browsers on the market. I was a PC devotee from ‘95 to ‘16, since then, it’s been all Tim Cook 🍎 all the time. My only regret is not purchasing a smartphone back in ‘07 from Steve Jobs. Presently, I own an iPhone 6s Plus in rose gold (2016), iPad Mini (2016), iPad Pro (2019) & MacBook (2018) in rose gold with matching Beats By Dre headphones. All four are set up with Safari, not Chrome, TOR, Brave, Edge, or DDGo. I love the ability to quickly save favorites, add to reading list & share content to other platforms. My favorites are alphabetized for quick reference & the reading list keeps all articles & pages in chronological order for quick recall. Also, I learned Safari quickly because it’s extremely user friendly. The browser helped my navigation of Apple when switching from PC. I’ll admit, learning MacBook isn’t easy, but, Safari keeps things familiar for me on the desktop. When lost, just go back to Safari & start over. It’s surprising no one in tech media mentions Safari more often as a go to source for navigating the internet. Chrome is the reigning king of, Land Of Browsers, without an heir apparent. I nominate Safari as the prince with future king potential. Citizens of Land Of Browsers don’t like their chrome-plated dirty laundry aired, sold or tracked.
I have been using this for years and had no problems with it. I ran over my phone with my lawn mower and was without my phone for over a year due to having to fight with the insurance company. However when I finally got a lawyer involved the insurance company finally replaced it for me. I DID not lose anything and I mean anything. I like the cards better because they are easier to clear out. You have to back everything up to your cloud every day or every other day so that you don’t have to worry about losing anything. As I always make sure that I back everything up just in case. It is not apples fault if you lose your any of your information it is yours for not backing up your phone to your cloud. So most of the people who write bad reviews either don’t back up or they just don’t or they just don’t care. Apple doesn’t charge a lot to add more space to your cloud so there is no reason why you can’t back you things. This is better than anything that google has. By far. If you want your information used by third parties then use google’s and quit complaining. You can change your browser in safari so that you don’t have to use them get with it you bad reviews and learn how to use safari.

App Privacy

The developer, Apple , indicated that the app’s privacy practices may include handling of data as described below. For more information, see the developer’s privacy policy .

Data Linked to You

The following data may be collected and linked to your identity:

  • User Content
  • Identifiers

Data Not Linked to You

The following data may be collected but it is not linked to your identity:

  • Browsing History
  • Diagnostics

Privacy practices may vary, for example, based on the features you use or your age. Learn More

Information

English, Arabic, Catalan, Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hebrew, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean, Malay, Norwegian Bokmål, Polish, Portuguese, Romanian, Russian, Simplified Chinese, Slovak, Spanish, Swedish, Thai, Traditional Chinese, Turkish, Ukrainian, Vietnamese

  • Developer Website
  • App Support
  • Privacy Policy

More By This Developer

Apple Books

Apple Podcasts

Find My Friends

Shazam: Find Music & Concerts

You Might Also Like

FRITZ!App WLAN

ADAC Pannenhilfe

Porn Shield-Block Ad in Safari

あんしんフィルター for au

France Identité

If Safari isn't loading websites or quits on your iPhone, iPad or iPod touch

If you can't load a website or web page, or Safari quits unexpectedly, follow these steps.

Connect to a different network

Try to load a website, such as www.apple.com/uk , using mobile data. If you don’t have mobile data, connect to a different Wi-Fi network , then load the website.

If you're using a VPN (Virtual Private Network), check your VPN settings . If you have a VPN turned on, some apps or websites may block content from being loaded.

Restart your device

Turn off your device and turn it on again.

Restart your iPhone

Restart your iPad

Restart your iPod touch

Clear website data

You can clear website data every so often to improve Safari performance.

Go to Settings > Safari.

Tap Clear History and Website Data.

Tap Clear History to confirm.

Turn on JavaScript

Turn on JavaScript if it's not already on.

Go to Settings > Safari > Advanced.

Turn on JavaScript.

Get more help

If the issue continues and only affects a certain website or web page, check if you have Private Relay turned on. You can temporarily turn off Private Relay in iCloud Settings . If Safari still doesn't load websites and you've tried all these steps, contact the website developer for more help.

unload safari

Contact Apple Support

Need more help? Save time by starting your support request online and we'll connect you to an expert.

How to quickly translate web pages in Safari on iOS and iPadOS

Easily translate web pages in Safari for iPhone and iPad.

How to translate web pages in Safari for iPhone and iPad.

What you'll need

  • How to translate web pages in Safari in iOS 16 and iPadOS 16

How to activate the Microsoft Translator extension in Safari

How to translate a web page on iphone with microsoft translator.

If you're running iOS 17 , Safari now comes with a translation feature baked into the browser, making it easier than ever to translate a web page on iPhone and iPad.

Once enabled, text is translated in-line on the webpage that you're viewing. It's a handy tool if you want to read websites that are written in different languages, and it's available right in the address bar in Safari.

With this in mind, here's how you can translate web pages in Safari on iPhone and iPad.

iPhone 15 Pro, iPad 9th gen, and Apple Watch SE for free at Verizon

iPhone 15 Pro, iPad 9th gen, and Apple Watch SE for free at Verizon

Choose Verizon's Unlimited Ultimate Plan and trade in an old device to get Apple's iPhone 15 Pro , iPad 9 , and an Apple Watch SE for absolutely nothing. A fantastic deal if you're looking to upgrade all of your Apple devices.

iPad Pro M4 | $999

iPad Pro M4 | $999

The brand-new iPad Pro M4 is the best tablet Apple has ever released. With an OLED display and the fastest chip Apple has ever made, this is a very powerful iPad.

How to translate a web page on iPhone in iOS 16 and iPadOS 16

In iOS 15 and later, the ability to translate a web page's language to your native language is now a built-in part of Safari. As such, you no longer need a third-party app to translate. Here's how to use built-in language translation in Safari in iOS 14, iOS 15, and later.

  • Tap the action button on the left side of the address bar while visiting a site that you need to translate. The button looks like two A's next to each other.
  • Tap Translate to [Your Device Language] .

Translate webpages in iOS 14, showing how to tap the action button, then tap Translate to English

  • Tap Enable Translation if prompted.

Your page will then be translated into the primary language that you've set on your device. If you want to revert back to the page's original language, take the following steps.

  • Tap the translate button in the Safari address bar. It takes the place of the standard action button on the left side of the address bar.
  • Tap View Original .

Translate webpages in iOS 14, showing how to tap the translate button, then tap View Original

The page will revert to its original language.

If you're running a version of iOS 13 or earlier on your device, then a third-party app with a translation extension is what you'll want to use. Microsoft's Translator extension is an excellent tool for the task, as it translates the web page in place when activated.

Master your iPhone in minutes

iMore offers spot-on advice and guidance from our team of experts, with decades of Apple device experience to lean on. Learn more with iMore!

Microsoft Translator

Microsoft Translator

Microsoft Translator is a great third-party solution for translating web pages, and its translations take place in-line on the web, rather than taking you to another, translated version of the page like some other apps.

Once you've got it downloaded, you can set up the action extension for translation web pages.

  • Open Safari on your iPhone or iPad.
  • While viewing a web page, tap the share button .
  • Scroll to the left on the bottom row of icons.

Activate Microsoft Translator extension, showing how to open Safari, tap the share button, then scroll to the left

  • Tap the More button.
  • Turn the switch next to Microsoft Translator to the green 'on' position.

Activate Microsoft Translator extension, showing how to tap More, turn on the switch, then tap Done

Now that you have the app installed, you can use it in Safari from the share menu.

  • Head to the web page that you want to translate.

Translate a page, showing how to open Safari, then head to the page

  • Tap the share button at the bottom of the display.
  • Tap the Microsoft Translator button. The extension will then translate the entire page for you.

Translate a page, showing how to tap the share button, then tap Microsoft Translator

Joseph Keller is the former Editor in Chief of iMore. An Apple user for almost 20 years, he spends his time learning the ins and outs of iOS and macOS, always finding ways of getting the most out of his iPhone, iPad, Apple Watch, and Mac.

How to customize your app icons with the Shortcuts app

iOS 18's massive Siri AI overhaul just leaked, but don't expect the best changes until 2025

Google breaks silence over AI search results that told people to eat rocks, put glue on pizza

  • Annie_M Thank you for this... it's good to know. Reply
  • View All 1 Comment

Most Popular

  • 2 Fans think Apple TV price drop could mean new model is imminent
  • 3 'Where Cards Fall' joins Apple Vision Pro games lineup for Arcade members
  • 4 Satechi's new Thunderbolt 4 Dock is a dream companion for your MacBook
  • 5 I didn't believe the hype about this Apple TV Plus show — I was so wrong, don't make the same mistake I did

unload safari

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

BeforeUnloadEvent

The BeforeUnloadEvent interface represents the event object for the beforeunload event, which is fired when the current window, contained document, and associated resources are about to be unloaded.

See the beforeunload event reference for detailed guidance on using this event.

Instance properties

Inherits properties from its parent, Event .

When set to a truthy value, triggers a browser-controlled confirmation dialog asking users to confirm if they want to leave the page when they try to close or reload it. This is a legacy feature, and best practice is to trigger the dialog by invoking event.preventDefault() , while also setting returnValue to support legacy cases.

Instance methods

Inherits methods from its parent, Event .

In the following example we have an HTML text <input> to represent some data that could be changed and require saving:

Our JavaScript attaches an input event listener to the <input> element that listens for changes in the inputted value. When the value is updated to a non-empty value, a beforeunload event listener is attached to the Window object.

If the value becomes an empty string again (i.e. the value is deleted), the beforeunload event listener is removed again — as mentioned above in the Usage notes , the listener should be removed when there is no unsaved data to warn about.

The beforeunload event handler function invokes event.preventDefault() to trigger the warning dialog when the user closes or navigates the tab. We have also included event.returnValue = true in the handler function so that any browsers that don't support the event.preventDefault() mechanism will still run the demo correctly.

When the <input> value is non-empty, if you try to close, navigate, or reload the page the browser displays the warning dialog. Try it out:

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • beforeunload event

DB-City

  • Bahasa Indonesia
  • Eastern Europe
  • Moscow Oblast

Elektrostal

Elektrostal Localisation : Country Russia , Oblast Moscow Oblast . Available Information : Geographical coordinates , Population, Area, Altitude, Weather and Hotel . Nearby cities and villages : Noginsk , Pavlovsky Posad and Staraya Kupavna .

Information

Find all the information of Elektrostal or click on the section of your choice in the left menu.

  • Update data

Elektrostal Demography

Information on the people and the population of Elektrostal.

Elektrostal Geography

Geographic Information regarding City of Elektrostal .

Elektrostal Distance

Distance (in kilometers) between Elektrostal and the biggest cities of Russia.

Elektrostal Map

Locate simply the city of Elektrostal through the card, map and satellite image of the city.

Elektrostal Nearby cities and villages

Elektrostal weather.

Weather forecast for the next coming days and current time of Elektrostal.

Elektrostal Sunrise and sunset

Find below the times of sunrise and sunset calculated 7 days to Elektrostal.

Elektrostal Hotel

Our team has selected for you a list of hotel in Elektrostal classified by value for money. Book your hotel room at the best price.

Elektrostal Nearby

Below is a list of activities and point of interest in Elektrostal and its surroundings.

Elektrostal Page

Russia Flag

  • Information /Russian-Federation--Moscow-Oblast--Elektrostal#info
  • Demography /Russian-Federation--Moscow-Oblast--Elektrostal#demo
  • Geography /Russian-Federation--Moscow-Oblast--Elektrostal#geo
  • Distance /Russian-Federation--Moscow-Oblast--Elektrostal#dist1
  • Map /Russian-Federation--Moscow-Oblast--Elektrostal#map
  • Nearby cities and villages /Russian-Federation--Moscow-Oblast--Elektrostal#dist2
  • Weather /Russian-Federation--Moscow-Oblast--Elektrostal#weather
  • Sunrise and sunset /Russian-Federation--Moscow-Oblast--Elektrostal#sun
  • Hotel /Russian-Federation--Moscow-Oblast--Elektrostal#hotel
  • Nearby /Russian-Federation--Moscow-Oblast--Elektrostal#around
  • Page /Russian-Federation--Moscow-Oblast--Elektrostal#page
  • Terms of Use
  • Copyright © 2024 DB-City - All rights reserved
  • Change Ad Consent Do not sell my data

Rusmania

  • Yekaterinburg
  • Novosibirsk
  • Vladivostok

unload safari

  • Tours to Russia
  • Practicalities
  • Russia in Lists
Rusmania • Deep into Russia

Out of the Centre

Savvino-storozhevsky monastery and museum.

Savvino-Storozhevsky Monastery and Museum

Zvenigorod's most famous sight is the Savvino-Storozhevsky Monastery, which was founded in 1398 by the monk Savva from the Troitse-Sergieva Lavra, at the invitation and with the support of Prince Yury Dmitrievich of Zvenigorod. Savva was later canonised as St Sabbas (Savva) of Storozhev. The monastery late flourished under the reign of Tsar Alexis, who chose the monastery as his family church and often went on pilgrimage there and made lots of donations to it. Most of the monastery’s buildings date from this time. The monastery is heavily fortified with thick walls and six towers, the most impressive of which is the Krasny Tower which also serves as the eastern entrance. The monastery was closed in 1918 and only reopened in 1995. In 1998 Patriarch Alexius II took part in a service to return the relics of St Sabbas to the monastery. Today the monastery has the status of a stauropegic monastery, which is second in status to a lavra. In addition to being a working monastery, it also holds the Zvenigorod Historical, Architectural and Art Museum.

Belfry and Neighbouring Churches

unload safari

Located near the main entrance is the monastery's belfry which is perhaps the calling card of the monastery due to its uniqueness. It was built in the 1650s and the St Sergius of Radonezh’s Church was opened on the middle tier in the mid-17th century, although it was originally dedicated to the Trinity. The belfry's 35-tonne Great Bladgovestny Bell fell in 1941 and was only restored and returned in 2003. Attached to the belfry is a large refectory and the Transfiguration Church, both of which were built on the orders of Tsar Alexis in the 1650s.  

unload safari

To the left of the belfry is another, smaller, refectory which is attached to the Trinity Gate-Church, which was also constructed in the 1650s on the orders of Tsar Alexis who made it his own family church. The church is elaborately decorated with colourful trims and underneath the archway is a beautiful 19th century fresco.

Nativity of Virgin Mary Cathedral

unload safari

The Nativity of Virgin Mary Cathedral is the oldest building in the monastery and among the oldest buildings in the Moscow Region. It was built between 1404 and 1405 during the lifetime of St Sabbas and using the funds of Prince Yury of Zvenigorod. The white-stone cathedral is a standard four-pillar design with a single golden dome. After the death of St Sabbas he was interred in the cathedral and a new altar dedicated to him was added.

unload safari

Under the reign of Tsar Alexis the cathedral was decorated with frescoes by Stepan Ryazanets, some of which remain today. Tsar Alexis also presented the cathedral with a five-tier iconostasis, the top row of icons have been preserved.

Tsaritsa's Chambers

unload safari

The Nativity of Virgin Mary Cathedral is located between the Tsaritsa's Chambers of the left and the Palace of Tsar Alexis on the right. The Tsaritsa's Chambers were built in the mid-17th century for the wife of Tsar Alexey - Tsaritsa Maria Ilinichna Miloskavskaya. The design of the building is influenced by the ancient Russian architectural style. Is prettier than the Tsar's chambers opposite, being red in colour with elaborately decorated window frames and entrance.

unload safari

At present the Tsaritsa's Chambers houses the Zvenigorod Historical, Architectural and Art Museum. Among its displays is an accurate recreation of the interior of a noble lady's chambers including furniture, decorations and a decorated tiled oven, and an exhibition on the history of Zvenigorod and the monastery.

Palace of Tsar Alexis

unload safari

The Palace of Tsar Alexis was built in the 1650s and is now one of the best surviving examples of non-religious architecture of that era. It was built especially for Tsar Alexis who often visited the monastery on religious pilgrimages. Its most striking feature is its pretty row of nine chimney spouts which resemble towers.

unload safari

Plan your next trip to Russia

Ready-to-book tours.

Your holiday in Russia starts here. Choose and book your tour to Russia.

REQUEST A CUSTOMISED TRIP

Looking for something unique? Create the trip of your dreams with the help of our experts.

Watch CBS News

Marian Robinson, mother of Michelle Obama, dies at 86

By Faris Tanyos

Updated on: June 1, 2024 / 1:15 PM EDT / CBS News

Marian Robinson, the mother of former first lady Michelle Obama, has died at the age of 86, her family announced Friday.

"She passed peacefully this morning, and right now, none of us are quite sure how exactly we'll move on without her," the statement read.

Official White House Portraits Of Barack And Michelle Obama Unveiled

Robinson was born in 1937 and grew up on Chicago's South Side, one of seven children. She trained as a teacher before working as a secretary. She married Fraser Robinson, and they had two children together, Michelle and Craig Robinson. Fraser died in 1991.

When her son-in-law, former President Barack Obama, won the presidency in 2008, she was coaxed by the family into leaving Chicago and moving into the White House.

"We needed her," the family's statement read Friday. "The girls needed her. And she ended up being our rock through it all."

In a 2018 interview with "CBS Mornings" alongside her daughter, she described the move as a "huge adjustment," but felt she needed to do it to help care for her granddaughters, Sasha and Malia Obama.  

"I felt like this was going to be a very hard life for both of them, and I … was worried about their safety. And I was worried about my grandkids," Robinson told "CBS Mornings."

However, Michelle Obama said her mother quickly became a "beloved figure" in the White House.

"She had a stream of people," Obama said back in 2018. "The butlers, the housekeepers. They would all stop by ... Grandma's room was like the confessional. You know, everyone would go there and just unload, you know? And then they'd leave. People still visit with mom in Chicago."

Following Obama's second term, Robinson returned to Chicago, "reconnecting with longtime friends, trading wise-cracks, traveling, and enjoying a good glass of wine," her family said.

In that 2018 interview, she said she did not miss the White House, just the people, "because they were like family to me."

"As a mother, she was our backstop, a calm and nonjudgmental witness to our triumphs and stumbles," the family said Friday. "She was always, always there, welcoming us back home no matter how far we had journeyed, with that deep and abiding love."

On Saturday, President Joe Biden and first lady Jill Biden said in a statement that Robinson was a "devoted mother and grandmother with a fierce and unconditional love of her family."

"With the blessing of friendship, we felt that love ourselves – with every quiet smile or warm embrace she shared with us," the Bidens said. "She believed, like we do, that family is the beginning, middle and end. She moved into the White House to be there for her family when they needed her the most, and in so doing, she served her country right alongside them. Her life is a reminder that we are a great nation because we are a good people."

— Jessica Kegu contributed to this report.

  • Michelle Obama

Faris Tanyos is a news editor for CBSNews.com, where he writes and edits stories and tracks breaking news. He previously worked as a digital news producer at several local news stations up and down the West Coast.

More from CBS News

Michelle Troconis sentenced to 20 years in Jennifer Dulos murder conspiracy

Trump lawyer eager to move forward with appeal of New York conviction

Book excerpt: "This Strange Eventful History" by Claire Messud

Trump, Biden debate will face obstacles in bypassing commission, co-chair predicts

Services & Software

unload safari

Get Microsoft's upgraded Pro OS for a small fraction of the regular price, but only while the sale lasts.

unload safari

Our Top Picks

From VPNs to playlists for your pup, here’re all the best services and software of 2023.

unload safari

Latest Stories

We help you decide which services to keep, try or cancel.

unload safari

Peacock Is Offering a Year of Streaming for $20

unload safari

No, You Can't Disable Google AI Overviews. But There Are Tricks to Avoid It

unload safari

Ticketmaster Breach: What We Know So Far

unload safari

Tired of Stale Netflix Picks? Browse 36,000 Categories With Netflix's Secret Menu

unload safari

How to Opt Out of Instagram and Facebook Using Your Posts for AI

unload safari

Superhuman Aims to Supercharge Your Email With an AI Assist

unload safari

Watch the No. 1 Trending Movie on Netflix: 'Godzilla Minus One'

unload safari

Spotify Increases Prices for Second Time in a Year

unload safari

I Became a Creator 10 Years Ago. How AI Makes It More Possible Than Ever

unload safari

Best VPN Service 2024: VPNs Tested by Our Experts

COMMENTS

  1. Is there any way to use window.onbeforeunload on Mobile Safari for iOS

    I was having the same problem. it seems safari browser in iphone triggers only focus and blur events and almost every other event is not triggered, e.g.(pagehide, pageshow, visibility change) but the good news is focus and blur event are supported and triggered on iphone, ipad & android mobiles as well.

  2. If Safari isn't loading websites or quits on your iPhone, iPad, or iPod

    Connect to a different network. Try to load a website, like www.apple.com, using cellular data. If you don't have cellular data, connect to a different Wi-Fi network, then load the website. If you're using a VPN (Virtual Private Network), check your VPN settings. If you have a VPN turned on, some apps or websites might block content from loading.

  3. javascript

    More oddly, if you have a confirm() call in your onunload(), and the user has clicked a link to go somewhere else, you are in business. If, however, the user closes the iPad Safari browser tab, the onunload() event will fire, but your confirm() will have an implicit cancel as response.

  4. Window: unload event

    The unload event is fired when the document or a child resource is being unloaded. It is fired after: beforeunload (cancelable event) pagehide. The document is in the following state: All the resources still exist (img, iframe etc.) Nothing is visible anymore to the end user. UI interactions are ineffective ( window.open, alert, confirm, etc.)

  5. Sure you want to leave?—browser beforeunload event

    Unload Basics If you want to prompt or warn your user that they're going to close your ... 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 ...

  6. Safari 15 prompts the beforeunload…

    Boosts 1. Views 3.2k. Participants 1. Using the example provided by MDN, the beforeunload event is working in my Safari browser: const beforeUnloadListener = (event) => {. event.preventDefault(); return event.returnValue = "Are you sure you want to exit?";

  7. Safari

    Support app. Get personalized access to solutions for your Apple products. Download the Apple Support app. Learn more about all the topics, resources, and contact options you need to download, update and manage your Safari settings.

  8. Safari

    Safari. Blazing fast. Incredibly private. Safari is the best way to experience the internet on all your Apple devices. It brings robust customization options, powerful privacy protections, and optimizes battery life — so you can browse how you like, when you like. And when it comes to speed, it's the world's fastest browser. 1.

  9. Window: beforeunload event

    Window: beforeunload event. The beforeunload event is fired when the current window, contained document, and associated resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. The main use case for this event is to trigger a browser-generated confirmation dialog that asks users to ...

  10. Window: pagehide event

    Like the unload and beforeunload events, this event is not reliably fired by browsers, especially on mobile. For example, the pagehide event is not fired at all in the following scenario: . A mobile user visits your page. The user then switches to a different app. Later, the user closes the browser from the app manager.

  11. Back/forward cache

    Adding an unload event listener will make your site slower in Firefox, and the code won't even run most of the time in Chrome and Safari. Due to its unreliability, and the performance impact for bfcache, Chrome is looking to deprecate the unload event. Use Permission Policy to prevent unload handlers being used on a page

  12. ‎Safari on the App Store

    With Safari you can browse sites, translate web pages, and access your tabs across iOS, iPadOS, and macOS. Features. • Passwords, bookmarks, history, tabs and more seamlessly sync across iPhone, iPad and Mac. • Private Browsing mode doesn't save your history and keeps your browsing your business. • Intelligent Tracking Prevention ...

  13. If Safari isn't loading websites or quits on your iPhone, iPad or iPod

    If Safari still doesn't load websites and you've tried all these steps, contact the website developer for more help. Published Date: January 01, 2024. Helpful? Yes No Character limit: 250. Maximum character limit is 250. Please don't include any personal information in your comment. ...

  14. How to quickly translate web pages in Safari on iOS and iPadOS

    Here's how to use built-in language translation in Safari in iOS 14, iOS 15, and later. Tap the action button on the left side of the address bar while visiting a site that you need to translate. The button looks like two A's next to each other. Tap Translate to [Your Device Language]. (Image credit: iMore)

  15. Elektrostal

    In 1938, it was granted town status. [citation needed]Administrative and municipal status. Within the framework of administrative divisions, it is incorporated as Elektrostal City Under Oblast Jurisdiction—an administrative unit with the status equal to that of the districts. As a municipal division, Elektrostal City Under Oblast Jurisdiction is incorporated as Elektrostal Urban Okrug.

  16. BeforeUnloadEvent

    The beforeunload event handler function invokes event.preventDefault() to trigger the warning dialog when the user closes or navigates the tab. We have also included event.returnValue = true in the handler function so that any browsers that don't support the event.preventDefault() mechanism will still run the demo correctly. js.

  17. Elektrostal

    Elektrostal. Elektrostal ( Russian: Электроста́ль) is a city in Moscow Oblast, Russia. It is 58 kilometers (36 mi) east of Moscow. As of 2010, 155,196 people lived there.

  18. Elektrostal, Moscow Oblast, Russia

    Elektrostal Geography. Geographic Information regarding City of Elektrostal. Elektrostal Geographical coordinates. Latitude: 55.8, Longitude: 38.45. 55° 48′ 0″ North, 38° 27′ 0″ East. Elektrostal Area. 4,951 hectares. 49.51 km² (19.12 sq mi) Elektrostal Altitude.

  19. Savvino-Storozhevsky Monastery and Museum

    Zvenigorod's most famous sight is the Savvino-Storozhevsky Monastery, which was founded in 1398 by the monk Savva from the Troitse-Sergieva Lavra, at the invitation and with the support of Prince Yury Dmitrievich of Zvenigorod. Savva was later canonised as St Sabbas (Savva) of Storozhev. The monastery late flourished under the reign of Tsar ...

  20. Marian Robinson, mother of Michelle Obama, dies at 86

    By Faris Tanyos. Updated on: June 1, 2024 / 1:15 PM EDT / CBS News. Marian Robinson, the mother of former first lady Michelle Obama, has died at the age of 86, her family announced Friday. "She ...

  21. javascript

    It works fine on Google Chrome and Firefox, but not on Safari. Thanks! javascript; jquery; html; css; safari; Share. Improve this question. Follow edited Dec 6, 2016 at 12:48. Paul Z. asked Dec 2, 2016 at 18:24. Paul Z. Paul Z. 895 2 2 gold badges 10 10 silver badges 28 28 bronze badges. 8.

  22. Services & Software

    All the news and tips you need to get the most out of services, apps and software you use every day. Explore by Topics. All Tech Mobile Home Entertainment VPN Computing Services & Software Gaming ...

  23. Why is jQuery unload not working in chrome and safari?

    jQuery's unload works well in chrome too, with the exception that Chrome doesn't allow alerts within it. I've used it to set cookies. And if it works with Chrome hope it works in Safari too.