Для чего нужна и не опасна ли фоновая синхронизация в Хроме?
Переключатель предлагает "разрешать недавно закрытым сайтам завершать отправку и получение данных". Зачем? Если я сайт закрыл, значит закончил там дела. Что он может с чем синхронизировать там? Я так вижу, что единственное для чего эта функция действительно нужна — так это чтобы сайт даже после закрытия мог продолжить атаковать компьютер. Переубедите меня, пожалуйста.
Я с вами целиком и полностью согласен, если вы закрыли браузер, сайт, следовательно вы закончмли с ним работать. Может и есть исключительные случаи, в которых эта функция поможет, однако в остальных случаях, это будет грузить интернет(как минимум).
После того, как вы завершили работу в Google Chrome, есть приложения и некоторые расширения,
которые продолжают работать и выполнять свои функции, что бы обеспечить большую функциональность.
Например проверка почты и т.д.
Конечно для выполнения этих функций расходуется энергегия и занят
В Диспедчере задач у вас есть возможность увидеть какие приложения
работают в фоновом режиме.
Если вы сомневаетесь, в том что вам нужно, чтобы продолжали работать некоторые программы
Web Background Synchronization
Copyright © 2021 the Contributors to the Web Background Synchronization Specification, published by the Web Platform Incubator Community Group under the W3C Community Contributor License Agreement (CLA). A human-readable summary is available.
Abstract
This specification describes a method that enables web applications to synchronize data in the background.
Status of this document
This specification was published by the Web Platform Incubator Community Group. It is not a W3C Standard nor is it on the W3C Standards Track. Please note that under the W3C Community Contributor License Agreement (CLA) there is a limited opt-out and other conditions apply. Learn more about W3C Community and Business Groups.
1. Introduction
This section is non-normative.
Web Applications often run in environments with unreliable networks (e.g., mobile phones) and unknown lifetimes (the browser might be killed or the user might navigate away). This makes it difficult to synchronize client data from web apps (such as photo uploads, document changes, or composed emails) with servers. If the browser closes or the user navigates away before synchronization can complete, the app must wait until the user revisits the page to try again. This specification provides a new onsync service worker event which can fire in the background so that synchronization attempts can continue despite adverse conditions when initially requested. This API is intended to reduce the time between content creation and content synchronization with the server.
As this API relies on service workers, functionality provided by this API is only available in a secure context.
In the above example addChatMessageToOutbox is a developer-defined function.
Reacting to a sync event within a service worker:
In the above example getMessagesFromOutbox and removeMessagesFromOutbox are developer-defined functions.
2. Concepts
The sync event is considered to run if no service worker clients whose frame type is top-level or auxiliary exist for the origin of the corresponding service worker registration.
The user agent is considered to be if the user agent has established a network connection. A user agent MAY use a stricter definition of being online. Such a stricter definition MAY take into account the particular service worker or origin a sync registration is associated with.
3. Constructs
A is a tuple consisting of a tag and a state.
A sync registration has an associated , a DOMString.
A sync registration has an associated , which is one of , , , or . It is initially set to pending.
A sync registration has an associated service worker registration. It is initially set to null.
4. Permissions Integration
5. Privacy Considerations
5.1. Permission
Note: Background sync SHOULD be enabled by default. Having the permission denied is considered an exceptional case.
5.2. Location Tracking
5.3. History Leaking
6. API Description
6.1. Extensions to the ServiceWorkerRegistration interface
In only one current engine.
The attribute exposes a SyncManager , which has an associated service worker registration represented by the ServiceWorkerRegistration on which the attribute is exposed.
6.2. SyncManager interface
In only one current engine.
In only one current engine.
The method, when invoked, MUST return a new promise promise and run the following steps in parallel:
- Let serviceWorkerRegistration be the SyncManager ‘s associated service worker registration.
- If serviceWorkerRegistration ’s active worker is null, reject promise with an InvalidStateError and abort these steps.
- If the user has disabled background sync, reject promise with an NotAllowedError and abort these steps.
- Let isBackground be true.
- For each client in the service worker clients for the serviceWorkerRegistration ’s origin:
- If client ’s frame type is top-level or auxiliary, set isBackground to false.
- If currentRegistration ’s registration state is waiting, set currentRegistration ’s registration state to pending.
- If currentRegistration ’s registration state is firing, set currentRegistration ’s registration state to reregisteredWhileFiring.
- Resolve promise .
- If the user agent is currently online and currentRegistration ’s registration state is pending, fire a sync event for currentRegistration .
- Let newRegistration be a new sync registration.
- Set newRegistration ’s associated tag to tag .
- Set newRegistration ’s associated service worker registration to serviceWorkerRegistration .
- Add newRegistration to serviceWorkerRegistration ’s list of sync registrations.
- Resolve promise .
- If the user agent is currently online, fire a sync event for newRegistration .
In only one current engine.
The method when invoked, MUST return a new promise promise and run the following steps in parallel:
- Let serviceWorkerRegistration be the SyncManager ‘s associated service worker registration.
- Let currentTags be a new sequence .
- For each registration in serviceWorkerRegistration ’s list of sync registrations, add registration ’s associated tag to currentTags .
- Resolve promise with currentTags .
6.3. The sync event
In only one current engine.
In all current engines.
In only one current engine.
Note: The SyncEvent interface represents a firing sync registration. If the page (or worker) that registered the event is running, the user agent will fire the sync event as soon as network connectivity is available. Otherwise, the user agent should run the event at the soonest convenience. If a sync event fails, the user agent may decide to retry it at a time of its choosing. The lastChance attribute is true if the user agent will not make further attempts to try this sync after the current attempt.
The above example reacts to lastChance by showing a notification to the user. This requires the origin to have permission to show notifications.
In the above example doImportantThing is a developer-defined function.
Whenever the user agent changes to online, the user agent SHOULD fire a sync event for each sync registration whose registration state is pending. The events may be fired in any order.
To for a sync registration registration , the user agent MUST run the following steps:
- Assert: registration ’s registration state is pending.
- Let serviceWorkerRegistration be the service worker registration associated with registration .
- Assert: registration exists in the list of sync registrations associated with serviceWorkerRegistration .
- Set registration ’s registration state to firing.
Fire Functional Event » sync » using SyncEvent on serviceWorkerRegistration with the following properties:
In only one current engine.
In only one current engine.
Then run the following steps with dispatchedEvent :
- Let waitUntilPromise be the result of waiting for all of dispatchedEvent ’s extended lifetime promises.
- Upon fulfillment of waitUntilPromise , perform the following steps atomically:
- If registration ’s state is reregisteredWhileFiring:
- Set registration ’s state to pending.
- If the user agent is currently online, fire a sync event for registration .
- Abort the rest of these steps.
- If registration ’s state is reregisteredWhileFiring:
- Set registration ’s state to pending.
- If the user agent is currently online, fire a sync event for registration .
- Abort the rest of these steps.
- Wait a user agent defined length of time.
- If registration ’s registration state is not waiting, abort these substeps.
- Set registration ’s registration state to pending.
- If the user agent is currently online, fire a sync event for registration .
A user agent MAY impose a time limit on the lifetime extension and execution time of a SyncEvent which is stricter than the time limit imposed for ExtendableEvent s in general. In particular an event for which lastChance is true MAY have a significantly shortened time limit.
A user agent a sync event based on some user agent defined heuristics.
Conformance
Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.
All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]
Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class=»example» , like this:
Informative notes begin with the word “Note” and are set apart from the normative text with class=»note» , like this:
Что такое фоновая синхронизация в браузере
Introducing Background Sync
Published on Tuesday, December 8, 2015 • Updated on Friday, September 22, 2017
Human boy working on web standards at Google
Background sync is a new web API that lets you defer actions until the user has stable connectivity. This is useful for ensuring that whatever the user wants to send, is actually sent.
# The problem
The internet is a great place to waste time. Without wasting time on the internet, we wouldn’t know cats dislike flowers, chameleons love bubbles, or that our very own Eric Bidelman is a putt putt golfing hero of the late 90s.
But sometimes, just sometimes, we’re not looking to waste time. The desired user experience is more like:
- Phone out of pocket.
- Achieve minor goal.
- Phone back in pocket.
- Resume life.
Unfortunately this experience is frequently broken by poor connectivity. We’ve all been there. You’re staring at a white screen or a spinner, and you know you should just give up and get on with your life, but you give it another 10 seconds just in case. After that 10 seconds? Nothing. But why give up now? You’ve invested time already, so walking away with nothing would be a waste, so you carry on waiting. By this point you want to give up, but you know the second you do so, is the second before everything would have loaded if only you’d waited.
Service workers solve the page loading part by letting you serve content from a cache. But what about when the page needs to send something to the server?
At the moment, if the user hits «send» on a message they have to stare at a spinner until it completes. If they try to navigate away or close the tab, we use onbeforeunload to display a message like, “Nope, I need you to stare at this spinner some more. Sorry”. If the user has no connection we tell the user “Sorry, you must come back later and try again”.
This is rubbish. Background sync lets you do better.
# The solution
The following video shows Emojoy, a simple emoji-only chat demo… thing. It’s a progressive web app. It works offline-first. It uses push messages and notifications, and it uses background sync.
If the user tries to send a message when they have zero connectivity, then, thankfully, the message is sent in the background once they get connectivity.
As of March 2016, Background sync is available in Chrome from version 49 and above. You can see it action by following the steps below:
-
.
- Go offline (either using airplane-mode or visit your local Faraday cage).
- Type a message.
- Go back to your home screen (optionally close the tab/browser).
- Go online.
- Message sends in the background!
Being able to send in the background like this also yields a perceived performance improvement. The app doesn’t need to make such a big deal about the message sending, so it can add the message to the output straight away.
# How to request a background sync
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Like push messaging, it uses a service worker as the event target, which enables it to work when the page isn’t open. To begin, register for a sync from a page:
Then listen for the event in /sw.js :
And that’s it! In the above, doSomeStuff() should return a promise indicating the success/failure of whatever it’s trying to do. If it fulfills, the sync is complete. If it fails, another sync will be scheduled to retry. Retry syncs also wait for connectivity, and employ an exponential back-off.
The tag name of the sync (‘myFirstSync’ in the above example) should be unique for a given sync. If you register for a sync using the same tag as a pending sync, it coalesces with the existing sync. That means you can register for an «clear-outbox» sync every time the user sends a message, but if they send 5 messages while offline, you’ll only get one sync when they become online. If you want 5 separate sync events, just use unique tags!
Here’s a simple demo that does the bare minimum; it uses the sync event to show a notification.
# What could I use background sync for?
Ideally, you’d use it to schedule any data sending that you care about beyond the life of the page. Chat messages, emails, document updates, settings changes, photo uploads… anything that you want to reach the server even if user navigates away or closes the tab. The page could store these in an «outbox» store in indexedDB, and the service worker would retrieve them, and send them.
Although, you could also use it to fetch small bits of data…
# Another demo!
This is the offline wikipedia demo I created for Supercharging Page Load. I’ve since added some background sync magic to it.
Try this out yourself. Make sure you are using Chrome 49 and above and then:
- Go to any article, perhaps Chrome.
- Go offline (either using airplane-mode or join a terrible mobile provider like I have).
- Click a link to another article.
- You should be told the page failed to load (this will also appear if the page just takes a while to load).
- Agree to notifications.
- Close the browser.
- Go online
- You get notified when the article is downloaded, cached, and ready to view!
Using this pattern, the user can put their phone in their pocket and get on with their life, knowing the phone will alert them when it’s fetched want they wanted.
# Permissions
The demos I’ve shown use web notifications, which require permission, but background sync itself does not.
Sync events will often complete while the user has a page open to the site, so requiring user permission would be a poor experience. Instead, we’re limiting when syncs can be registered and triggered to prevent abuse. E.g.:
- You can only register for a sync event when the user has a window open to the site.
- The event execution time is capped, so you can’t use them to ping a server every x seconds, mine bitcoins or whatever.
Of course, these restrictions may loosen/tighten based on real-world usage.
# Progressive enhancement
It’ll be a while before all browsers support background sync, especially as Safari and Edge don’t yet support service workers. But progressive enhancement helps here:
If service workers or background sync aren’t available, just post the content from the page as you’d do today.
Note that it’s worth using background sync even if the user appears to have good connectivity, as it protects you against navigations and tab closures during data send.
# The future
We’re aiming to ship background sync to a stable version of Chrome in the first half of 2016. But we’re also working on a variant, “periodic background sync”. This will allow you to request a “periodicsync” event restricted by time interval, battery state and network state. This would require user permission, of course, but it will also be down to the will of the browser for when and how often these events fire. E.g., a news site could request to sync every hour, but the browser may know you only read that site at 07:00, so the sync would fire daily at 06:50. This idea is a little further off than one-off syncing, but it’s coming.
Bit by bit we’re bringing successful patterns from Android/iOS onto the web, while still retaining what makes the web great!
Что такое фоновая синхронизация в хроме?
Лучше всего будет работать фоновая синхронизация, она отправляет запрос, даже если пользователь ушел с исходной страницы. . Мы хотим, чтобы пользователь мог подписаться на нашу новостную рассылку независимо от того, есть ли у него в настоящее время доступ к Интернету.
Как отключить резервирование на Xiaomi?
Во вкладке «Резервирование системы» выбираем «Локальное резервирование». В самом низу жмем «Создать резервную копию». В меню выбора объектов резервирования жмем «>» напротив каждой из категорий и снимаем галочки с тех функций или приложений, резервирование которых производить не надо.
Как отключить оптимизацию MIUI?
Отключаем Оптимизацию Итак, заходим в раздел для разработчиков, крутим список настроек до пункта «Оптимизация MIUI» и просто отключаем переключатель. Вот так вы можете скорректировать работу вашего смартфона.
Что будет если отключить оптимизацию MIUI?
Что будет, если отключить оптимизацию MIUI Он перестанет принудительно выгружать приложения из памяти, затормаживать процессор с целью увеличения автономности и выполнять другие задачи, которые, по мнению системы, обеспечивают правильную работоспособность смартфона и приложений, которые на нём запускаются.
Как отключить оптимизацию MIUI на Redmi note 10?
2:094:01Рекомендуемый клип · 60 сек.Начало рекомендуемого клипаКонец рекомендуемого клипа
- If registration ’s state is reregisteredWhileFiring: